Koko Eating Bananas
Master this topic with zero to advance depth.
Koko Eating Bananas
Koko loves to eat bananas. There are n piles of bananas, the i-th pile has piles[i] bananas. The guards will come back in h hours. Koko can decide her bananas-per-hour eating speed k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Return the minimum integer k such that she can eat all the bananas within h hours.
Examples
Level I: Brute Force
Intuition
Try every speed k starting from 1 upwards until we find one that allows Koko to finish in h hours.
Detailed Dry Run
piles=[3,6,7,11], h=8. Try k=1, 2, 3... until 4 fits.
Level III: Optimal (Binary Search on Answer)
Intuition
The time spent eating is a monotonic function of the speed k. We can binary search in the range [1, max(piles)].
Detailed Dry Run
piles=[3,6,7,11], h=8. L=1, R=11.
- Mid 6: 1+1+2+2 = 6 <= 8. R=6.
- Mid 3: 1+2+3+4 = 10 > 8. L=4.
- Mid 5: 1+2+2+3 = 8 <= 8. R=5.
- Mid 4: 1+2+2+3 = 8 <= 8. R=4. Result 4.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.