Python 1705.py
class Solution:
def eatenApples(self, apples: List[int], days: List[int]) -> int:
result = 0
have = [] # min-heap, ordered by day of decay
today = -1 # current day, incremented at start of loop => first day is 0
while True:
today += 1
# add fresh apples
if today < len(apples) and apples[today] > 0:
heappush(have, ( today + days[today], apples[today] ))
# remove rotten apples
while have and have[0][0] <= today:
heappop(have)
# no more apples
if not have:
# there will be more apples some day
if today < len(apples):
continue
return result
# eat an apple
decay, num = heappop(have)
result += 1
num -= 1
# put back remaining apples
if num > 0:
heappush(have, ( decay, num ))
Difficulty
and has an acceptance rate of about 44% (80k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Heap (Priority Queue)
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of maximizing the number of apples that can be eaten given two parallel arrays: apples, which indicates how many apples grow on each day, and days, which specifies the number of days each batch remains edible. The algorithm proceeds day by day, maintaining a priority queue (min-heap) of apple batches ordered by their expiration day. On each day it adds newly grown apples, discards any batches that have already rotted, and consumes one apple from the batch that will rot soonest. The process terminates when there are no more apples to eat and no future batches will appear.
Core Loop
The heart of the solution is an infinite while True loop that increments a day counter at the start of each iteration.
today = -1
while True:
today += 1
...
By initializing today to -1 and incrementing it immediately, the first logical day processed is 0, matching the zero-based indexing of the input arrays.
Adding Fresh Apples
At the beginning of each day the algorithm checks whether a new batch of apples appears. If the current day index is within the bounds of the apples list and the batch size is positive, the batch is inserted into the heap with a tuple containing its expiration day (today + days[today]) and the number of apples.
if today < len(apples) and apples[today] > 0:
heappush(have, (today + days[today], apples[today]))
This step ensures that only non-empty batches are tracked and that the expiration day is pre-computed for efficient comparison later.
Discarding Rotten Apples
Before attempting to eat an apple, the algorithm removes any batches whose expiration day is less than or equal to the current day. The heap’s ordering guarantees that the batch with the earliest expiration is examined first, and the loop continues until the top of the heap is still valid.
while have and have[0][0] <= today:
heappop(have)
By performing this cleanup early, the algorithm avoids counting rotten apples and keeps the heap size minimal.
Detecting Completion
If the heap becomes empty after discarding rotten batches, the algorithm determines whether more apples might appear in the future. When the current day is still within the range of the input arrays, it simply proceeds to the next day, allowing later batches to be added. If the day index has already passed the length of the apples list, there are no future batches, and the accumulated result is returned.
if not have:
if today < len(apples):
continue
return result
This conditional flow handles the case where there is a temporary gap with no available apples but later growth is scheduled.
Eating an Apple
When at least one viable batch exists, the algorithm extracts the batch with the nearest expiration, consumes a single apple, and updates the total count. The remaining quantity of that batch is decremented, and if any apples remain, the batch is re-inserted into the heap with the same expiration day.
decay, num = heappop(have)
result += 1
num -= 1
if num > 0:
heappush(have, (decay, num))
Because the heap is ordered by expiration, this greedy choice guarantees that apples closest to rotting are prioritized, which is essential for maximizing the total eaten count.
Edge Cases Handled
The implementation gracefully handles several boundary conditions. When a day’s apples entry is zero, the if guard prevents an empty batch from entering the heap, avoiding unnecessary heap operations. If days[today] is zero, the computed expiration equals the current day, causing the batch to be removed immediately by the “discard rotten apples” loop, effectively treating the batch as never edible.
When the input arrays are of different lengths, the condition today < len(apples) ensures that the algorithm never accesses out-of-range indices, and the early-continue logic allows the loop to skip days without new growth while still checking for existing batches.
If all batches become rotten on a particular day, the heap empties, triggering the completion check. The algorithm then either continues (if future growth is pending) or returns the final count, correctly handling scenarios where there are long stretches without any apples.
The case where multiple batches share the same expiration day is also covered: the heap may contain several entries with identical decay values, and the heappop operation will retrieve one of them arbitrarily; the subsequent re-insertion of any remaining apples preserves the correct ordering for later days.
Performance Optimizations
The use of a min-heap (have) is a central optimization. By always keeping the batch with the earliest expiration at the top, the algorithm can decide in constant time which apple to eat, while insertion and removal operations remain logarithmic in the number of active batches. This avoids scanning the entire list of batches each day.
The inner loop that discards rotten apples runs only while the top of the heap is expired, which means each batch is removed at most once. Consequently, the total number of heap deletions is bounded by the number of batches inserted, preventing redundant work.
The early-continue when the heap is empty but future apples are expected prevents unnecessary iterations over days where no action is possible. Instead of iterating through every remaining day, the loop simply advances to the next day, allowing the next batch to be added as soon as it appears.
Re-inserting a partially consumed batch only when num > 0 avoids pushing empty entries back onto the heap, keeping the heap size as small as possible throughout execution.
Overall, the algorithm balances the need to process each day sequentially with data-structure-driven shortcuts that limit the amount of work performed per day to a small, predictable set of heap operations.
ELI5 - Simplified Explanation
Imagine a magical basket that keeps track of all the apples collected. Every day, some new apples might arrive, and each one comes with a tiny sticker telling exactly which day it will go bad. The code acts like a helper who wants to eat as many good apples as possible before they spoil.
First, the helper looks at the calendar to see if any new apples have arrived. If they have, the helper puts them into the basket along with their expiration sticker. Next, the helper checks the basket to see if any apples have already turned brown and mushy. Any spoiled apples are taken out and tossed away so they do not get in the way.
If the basket is completely empty, the helper waits to see if more yummy apples are coming later. If no more apples will ever arrive, the helper stops working. When there are fresh apples in the basket, the helper picks the one that is going to spoil the fastest. After eating one apple, if there are still more of that same kind left, the helper puts them back into the basket to save for another snack. This pattern continues day by day, making sure that the freshest apples are always enjoyed before they run out of time.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | ||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1559: Detect Cycles in 2D Grid
- problem 1573: Number of Ways to Split a String
- problem 1626: Best Team With No Conflicts
- problem 1723: Find Minimum Time to Finish All Jobs
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality