Example 1
- Input
- piles = [3,6,7,11], h = 8
- Output
- 4
At 4 bananas per hour the piles take 1, 2, 2 and 3 hours, totalling exactly 8 hours. Speed 3 needs 1 + 2 + 3 + 4 = 10 hours, so 4 is the minimum, not just a feasible choice.
Given banana piles and a deadline of h hours, find the slowest hourly eating speed that still finishes every pile in time. Feasibility only improves as speed rises, so the minimum feasible speed is found by binary search.
Koko loves to eat bananas. There are n piles of bananas, the i-th 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. Return the minimum integer k such that she can eat all the bananas within h hours.
1 <= piles.length <= 10^4piles.length <= h <= 10^91 <= piles[i] <= 10^9At 4 bananas per hour the piles take 1, 2, 2 and 3 hours, totalling exactly 8 hours. Speed 3 needs 1 + 2 + 3 + 4 = 10 hours, so 4 is the minimum, not just a feasible choice.
With only 5 hours for 5 piles each pile must finish in one hour, so the speed must cover the largest pile.
At 23 bananas per hour the piles take 2, 1, 1, 1 and 1 hours, totalling exactly 6 hours. Speed 22 needs 2 + 1 + 2 + 1 + 1 = 7 hours, so 23 is the first feasible speed.
One banana and one hour give the smallest search interval [1, 1]; speed 1 finishes exactly on the deadline.
Speed 3 still takes two hours per pile, totalling 4. Speed 4 takes one hour per pile. Unused capacity in one hour cannot move to the next pile.
A pile needs whole hours: at speed 4, a pile of 7 takes two hours, even though the second hour is partly unused. That spare capacity cannot be spent on another pile. Therefore total hours are the sum of each pile's ceiling division, not the ceiling of the total bananas. Example 1 needs 1 + 2 + 2 + 3 = 8 hours at speed 4; speed 3 needs 10. Increasing speed can only reduce or preserve each pile's hours, creating an infeasible-then-feasible boundary to search.
Reveal Try Every Speed: intuition, complexity, and code
h equals the pile count, each pile must finish in one hour, so the answer is the largest pile.h.8 at speed 4 takes 2 hours, while a pile of 9 takes 3.h is at least the total bananas, speed 1 is feasible and minimal. Extra allowed hours need not be used.ceil(sum(piles) / k) incorrectly shares spare hourly capacity across piles; [4, 4], h = 3 needs speed 4, not 3.When a minimum feasible value has a monotone pass-fail test, binary search the answer range instead of the input: the first passing value is the optimum.