Koko Eating Bananas
Difficulty: Medium · Pattern: Binary Search · LeetCode #875
There are piles of bananas, piles[i] in pile i. Each hour, an eater picks one pile and eats up to k bananas from it (if the pile has fewer than k, they finish it and wait out the rest of that hour). Return the minimum integer speed k that lets them finish everything within h hours. It's guaranteed that h ≥ piles.length.
Examples
text
piles = [3, 6, 7, 11], h = 8 → 4
piles = [30, 11, 23, 4, 20], h = 5 → 30
piles = [30, 11, 23, 4, 20], h = 6 → 23Hints
- At speed k, pile p takes ⌈p / k⌉ hours. Total hours is easy to compute for a given k.
- If speed k works, any faster speed works too. That's monotonic.
- Search k in [1, max(piles)].
Approach
The predicate "speed k finishes within h hours" is false for small k and true from some point on. Binary search the first k in [1, max(piles)] where it's true. Each check sums ⌈p/k⌉ over the piles in O(n).
Complexity
Time: O(n · log(max pile)). Space: O(1).
Python solution
def minEatingSpeed(piles, h):
lo, hi = 1, max(piles)
while lo < hi:
k = (lo + hi) // 2
hours = sum((p + k - 1) // k for p in piles)
if hours <= h:
hi = k
else:
lo = k + 1
return loJavaScript solution
function minEatingSpeed(piles, h) {
let lo = 1, hi = Math.max(...piles);
while (lo < hi) {
const k = Math.floor((lo + hi) / 2);
let hours = 0;
for (const p of piles) hours += Math.ceil(p / k);
if (hours <= h) hi = k; else lo = k + 1;
}
return lo;
}