Maximum Number of Eaten Apples — LeetCode 1705 Python Solution

MediumGreedyArrayHeap (Priority Queue)
Problem
#1705
Reading time
4 min

The problem

There is a special kind of apple tree that grows apples every day for n days. On the ith 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.

Example

Input
apples = [1,2,3,5,2], days = [3,2,1,4,2]
Output
7
Explanation
You can eat 7 apples:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log n + M)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1705. Maximum Number of Eaten Apples is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1705. Maximum Number of Eaten Apples?
LeetCode 1705. Maximum Number of Eaten Apples is rated Medium on LeetCode.
What is the time complexity of LeetCode 1705. Maximum Number of Eaten Apples?
The Python solution on this page runs in O(n \times \log n + M).
What is the space complexity of LeetCode 1705. Maximum Number of Eaten Apples?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1705. Maximum Number of Eaten Apples cover?
LeetCode 1705. Maximum Number of Eaten Apples is tagged Greedy, Array and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview