Koko Eating Bananas
Koko loves to eat bananas. There are N piles of bananas, and the i-th pile has piles[i] bananas. The guards will return in h hours. Koko can decide her bananas-per-hour eating speed k. Each hour she chooses a pile and eats up to k bananas from it. If the pile has fewer than k bananas, she eats all of them and cannot continue to another pile that hour. Find the minimum integer k that allows Koko to eat all bananas within h hours.
This is a classic binary search on answer problem. The minimum possible speed is 1 (one banana per hour). The maximum is the largest pile (eating the biggest pile in one hour). Binary search across this range to find the smallest feasible speed.
Feasibility is determined by simulating the eating process at a given speed k. For each pile, compute the hours needed:ceil(pile / k). Sum the hours across all piles and check if the total is at most h. The ceiling division (pile + k - 1) / k avoids floating point.
Edge cases include h equal to the number of piles (speed must be at least max(piles)), very large piles requiring careful integer math, and h being larger than the number of piles allowing slower speeds.
Example Input & Output
5 hours means speed must equal max pile (30).
Speed 4 eats all in 8 hours.
Large pile, barely enough hours.
Four piles in four hours, speed 1 works.
Speed 23 finishes in 6 hours.
Algorithm Flow
Solution Approach
Koko eats bananas from piles, and each hour she can eat from one pile at a speed of k bananas per hour. Find the minimum k such that she can finish all bananas within h hours. Use binary search on the possible speed range [1, max(piles)]. For each candidate speed, compute the total hours needed by summing Math.ceil(pile / speed) for each pile. If the total exceeds h, increase speed; otherwise, try a lower speed.
The feasibility check (can she finish in h hours at speed mid) is the core of the binary search on answers pattern. The search range is bounded by the largest pile, since eating faster than that does not reduce the number of hours needed.
Time complexity is O(n log maxPile), space complexity is O(1).
Best Answers
class Solution {
public int solution(int[] piles, int h) {
int lo = 1, hi = 0;
for (int p : piles) if (p > hi) hi = p;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (can(piles, mid, h)) hi = mid;
else lo = mid + 1;
}
return lo;
}
private boolean can(int[] p, int k, int h) {
int hours = 0;
for (int v : p) hours += (v + k - 1) / k;
return hours <= h;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
