Maximum Number of Eaten Apples - 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.
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.
Input & Output
Example 1 — Basic Case
$
Input:
apples = [1,2,3,5], days = [3,2,1,4]
›
Output:
7
💡 Note:
Day 0: eat apple from batch 2 (expires day 2). Day 1: eat apple from batch 1 (expires day 3). Day 2: eat apple from batch 1 (expires day 3). Day 3: eat apple from batch 0 (expires day 3). Day 4: eat apple from batch 3 (expires day 7). Day 5: eat apple from batch 3. Day 6: eat apple from batch 3. Total: 7 apples.
Example 2 — Some Days No Apples
$
Input:
apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]
›
Output:
5
💡 Note:
Days 0-2: eat one apple each day from first batch (3 apples expire day 3). Days 3-4: no apples available. Day 5: add second batch (2 apples expire day 7). Days 5-6: eat from second batch. Total: 5 apples.
Example 3 — Single Day
$
Input:
apples = [1], days = [1]
›
Output:
1
💡 Note:
Day 0: eat the single apple (expires day 1). No more apples available after day 0. Total: 1 apple.
Constraints
- 1 ≤ n ≤ 2 × 104
- 0 ≤ apples[i] ≤ 2 × 104
- 1 ≤ days[i] ≤ 2 × 104
- apples[i] == 0 if and only if days[i] == 0
Visualization
Tap to expand
Understanding the Visualization
1
Input
Apple arrays: apples=[1,2,3,5], days=[3,2,1,4]
2
Process
Use greedy strategy with priority queue to eat expiring apples first
3
Output
Maximum apples eaten: 7
Key Takeaway
🎯 Key Insight: Always eat the apple that expires soonest to maximize total consumption before spoilage
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code