Leetcode #1705: Maximum Number of Eaten Apples
In this guide, we solve Leetcode #1705 Maximum Number of Eaten Apples in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Greedy, Array, Heap (Priority Queue)
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
Example
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.
Python Solution
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.