875. Koko Eating Bananas
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of 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.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k such that she can eat all the bananas within h hours.
Example 1:
Example 2:
Example 3:
- 1 <= piles.length <= 104
- piles.length <= h <= 109
- 1 <= piles[i] <= 109
Constraints:
Notes
Intuition
The eating speed ranges from 1 to max(piles). Binary search finds the minimum speed that lets Koko finish in time. Higher speeds always work if lower speeds work, so we're finding a threshold.
Implementation
Binary search on speed from 1 to max(piles). For each candidate speed, calculate total hours needed (sum of ceil(pile/speed) for each pile). If hours exceed h, we need more speed—search right. Otherwise, search left for potentially slower valid speeds. When the loop exits, l is the minimum valid speed.
Edge-cases
Use ceiling division because even one banana in a pile takes a full hour. The answer is l at the end, not r.
- Time: O(n log m) — where m is max(piles), binary search with O(n) validation
- Space: O(1) — only tracking pointers