Binary Search
Medium
Apple Harvest (Koko Variant)
Find the minimum eating speed to finish all piles within H hours.
20 min
Solve on LeetCodeProblem Understanding
You have n piles of apples. The i-th pile has piles[i] apples.
You have H hours to eat all apples.
You can decide your eating speed k (apples per hour).
- Each hour, you choose a pile and eat up to
kapples from it. - If the pile has less than
kapples, you eat them all and stop for that hour (you don't move to the next pile).
Return the minimum integer k such that you can eat all apples within H hours.
Example
- Piles:
[3, 6, 7, 11], H:8 - If k=1: Needs 3+6+7+11 = 27 hours (> 8). Too slow.
- If k=4: Needs 1+2+2+3 = 8 hours (<= 8). Valid.
- Can we do better? Minimum k is our goal.
Attempt 1: Brute Force (Linear Search on k)
The possible speeds range from k=1 (slowest) to k=max(piles) (fastest - one pile per hour).
We can check every k starting from 1.
- Try k=1. Calculate hours. If <= H, return 1.
- Try k=2. Calculate hours. If <= H, return 2.
- ...
Time Complexity
O(max(P) * n). If max pile is 10^9, this is TLE (Time Limit Exceeded).
The Intuition: Binary Search on Answer
The valid speeds form a monotonic range:
- If speed
kis valid (we finish in time), then any speed> kis also valid (we finish even faster). - If speed
kis invalid (too slow), then any speed< kis also invalid.
This monotonicity allow us to use Binary Search on the search space of k (from 1 to max(piles)).
- Range: [1, max(piles)]
- Mid: Test if speed
midis feasible.- If feasible (
hours <= H): Thismidcould be the minimum, but maybe there's a smaller one? Storemidas answer, and search left (high = mid - 1). - If not feasible (
hours > H): Too slow! Need faster speed. Search right (low = mid + 1).
- If feasible (
Interactive Visualization
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Example
- Attempt 1: Brute Force (Linear Search on k)
- The Intuition: Binary Search on Answer
- Interactive Visualization
- Dry Run
- The Solution Template
- Edge Cases
- Time & Space Analysis
- Summary
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
