Maximum Number of Eaten Apples Problem
Description
LeetCode Problem 1705.
There is a special kind of apple tree that grows apples every day for n days. On the i^th day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0.
You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days.
Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.
Example 1:
Input: apples = [1,2,3,5,2], days = [3,2,1,4,2]
Output: 7
Explanation: You can eat 7 apples:
- On the first day, you eat an apple that grew on the first day.
- On the second day, you eat an apple that grew on the second day.
- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.
- On the fourth to the seventh days, you eat apples that grew on the fourth day.
Example 2:
Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]
Output: 5
Explanation: You can eat 5 apples:
- On the first to the third day you eat apples that grew on the first day.
- Do nothing on the fouth and fifth days.
- On the sixth and seventh days you eat apples that grew on the sixth day.
Constraints:
n == apples.length == days.length1 <= n <= 2 * 10^40 <= apples[i], days[i] <= 2 * 10^4days[i] = 0if and only ifapples[i] = 0.
Solution
Approach: Greedy + Min-Heap
Each day, the best apple to eat is the one that rots soonest: the others will still be around later.
Keep a min-heap of (last edible day, apples left) batches. On day i, add that day's batch if it has apples, then drop batches whose last edible day is before i. If the heap is not empty, eat one apple from the top batch and put it back if it still has apples and does not rot today. Continue past day n until the heap is empty.
Complexity: O(n log n + M) time and O(n) space, where n is the length of days and M = max(days).
from heapq import heappop, heappush
class Solution:
def eatenApples(self, apples: List[int], days: List[int]) -> int:
n = len(days)
i = ans = 0
q = []
while i < n or q:
if i < n and apples[i]:
heappush(q, (i + days[i] - 1, apples[i]))
while q and q[0][0] < i:
heappop(q)
if q:
t, v = heappop(q)
v -= 1
ans += 1
if v and t > i:
heappush(q, (t, v))
i += 1
return ans