Binary search on the answer
Medium TimeO(n log m) SpaceO(1)
Koko has piles of bananas and limit hours before the guards return. At a chosen speed she eats from one pile an hour — finishing it, or taking that many from it — and never starts a second pile in the same hour, so an hour spent on a pile smaller than her speed is partly wasted. Return the slowest whole-banana speed that still clears every pile in time. There are always at least as many hours as piles, so some speed always works.
Examples
Example 1
- Input
- piles = [3, 6, 7, 11]limit = 8
- Output
- At 4 an hour the piles take
41 + 2 + 2 + 3= 8 hours, exactly the limit; at 3 they take 10.
Example 2
- Input
- piles = [3, 6, 7, 11]limit = 4
- Output
- Four hours for four piles is one pile an hour, so the speed has to reach the largest pile.
11
The Code
function hoursNeeded(piles, speed) {
let hours = 0;
for (let i = 0; i < piles.length; i++) {
hours += Math.ceil(piles[i] / speed);
}
return hours;
}
function minEatingSpeed(piles, limit) {
let low = 1;
let high = Math.max.apply(null, piles);
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (hoursNeeded(piles, mid) <= limit) high = mid;
else low = mid + 1;
}
return low;
}
minEatingSpeed([3, 6, 7, 11], 8);Done
The first 18 calls, of 30. This one does not fit on a page.
More like this
All searching examples (8) →- Binary search Halve the search range each step with lo / mid / hi.
- Linear search Scan left to right until you find the value.
- Rotated search Binary search where one half is always sorted — use it.
- Find peak Climb toward the higher neighbour — a peak must lie that way.
- Binary search (recursive) The same halving, written as a call tree instead of a loop.
- Insert position Binary search that returns where a value *would* go.