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
Maximum Number of Eaten Apples ProblemInput Arraysapples = [1,2,3,5]days = [3,2,1,4]Growth & expiry dataGreedy Strategy1. Add new apple batches to min-heap2. Remove expired batches3. Eat apple expiring soonestOutput7Maximum appleseatenDay 0: 1 appleexpires day 3(0+3=3)Day 1: 2 applesexpires day 3(1+2=3)Day 2: 3 applesexpires day 3(2+1=3)Day 3: 5 applesexpires day 7(3+4=7)Eat order: Day 2 batch → Day 1 batch → Day 0 batch → Day 3 batchTotal eaten: 3 + 2 + 1 + 1 = 7 apples
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
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
34.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen