Koko Eating Bananas - Problem
Koko the gorilla loves bananas! ๐ There are n piles of bananas scattered around, where the i-th pile contains piles[i] bananas. The guards have left and will return in exactly h hours.
Koko must decide on her eating speed k (bananas per hour). Each hour, she picks one pile and eats at most k bananas from it. If a pile has fewer than k bananas, she eats the entire pile and then takes a break for the rest of that hour.
Koko wants to eat slowly (she's a mindful eater!), but she also needs to finish all the bananas before the guards return. Your task is to find the minimum eating speed k that allows her to consume all bananas within h hours.
Input & Output
example_1.py โ Basic Case
$
Input:
piles = [3,6,7,11], h = 8
โบ
Output:
4
๐ก Note:
At speed 4: pile 3 takes 1h, pile 6 takes 2h, pile 7 takes 2h, pile 11 takes 3h. Total = 8h exactly.
example_2.py โ More Time Available
$
Input:
piles = [30,11,23,4,20], h = 5
โบ
Output:
30
๐ก Note:
With only 5 hours for 5 piles, Koko must eat the largest pile (30) in 1 hour, so minimum speed is 30.
example_3.py โ Plenty of Time
$
Input:
piles = [30,11,23,4,20], h = 6
โบ
Output:
23
๐ก Note:
At speed 23: piles take [2,1,1,1,1] hours respectively, totaling 6 hours exactly.
Constraints
- 1 โค piles.length โค 104
- piles.length โค h โค 109
- 1 โค piles[i] โค 109
- Key constraint: h โฅ piles.length (enough time to eat at least one pile per hour)
Visualization
Tap to expand
Understanding the Visualization
1
Define Search Space
Reading speed must be between 1 and the thickest book's pages
2
Test Middle Speed
For each book, calculate ceil(pages/speed) hours needed
3
Check Feasibility
If total time โค h, try slower speed; otherwise need faster speed
4
Narrow Search
Binary search eliminates half the possibilities each iteration
5
Find Minimum
Converge to the slowest speed that still meets the deadline
Key Takeaway
๐ฏ Key Insight: The problem has a monotonic property - if eating speed k works, then any speed > k also works. This allows us to binary search the answer space efficiently, reducing time complexity from O(max(piles) ร n) to O(log(max(piles)) ร n).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code