#1705

Maximum Number of Eaten Apples

Medium
ArrayGreedyHeap (Priority Queue)Heap (Priority Queue)Greedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses a priority queue (or max-heap) to efficiently track the apples that can be eaten based on their rot days. This allows us to always eat the apple that will rot the soonest, maximizing the total number of apples eaten.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a max-heap to keep track of available apples and their expiration days.
  2. 2Step 2: Iterate through each day, adding new apples to the heap.
  3. 3Step 3: On each day, check the heap for the apple that will rot the soonest and eat it if available.
  4. 4Step 4: Remove any rotten apples from the heap before eating.
solution.py18 lines
1# Full working Python code
2import heapq
3
4def maxEatenApples(apples, days):
5    max_heap = []
6    total_eaten = 0
7    for day in range(len(apples) + max(days)):
8        if day < len(apples) and apples[day] > 0:
9            heapq.heappush(max_heap, (day + days[day], apples[day]))
10        while max_heap and max_heap[0][0] <= day:
11            heapq.heappop(max_heap)  # Remove rotten apples
12        if max_heap:
13            total_eaten += 1
14            max_heap[0] = (max_heap[0][0], max_heap[0][1] - 1)
15            if max_heap[0][1] == 0:
16                heapq.heappop(max_heap)
17    return total_eaten
18

Complexity note: The complexity is O(n log n) due to the operations on the priority queue, where n is the number of days. Each insertion and deletion operation takes O(log n) time.

  • 1It's optimal to eat apples that will rot first, ensuring maximum consumption.
  • 2Using a priority queue helps efficiently manage which apples to eat based on their expiration.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.