Leetcode 875. 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 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 that hour.
Koko likes 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.
h
is at least as large as the number of piles?
h
is always greater than or equal to n
. This means it’s always possible to finish all the bananas in the given time.n
and h
?
1 <= n <= 10^4
and n <= h <= 10^9
.piles[i]
)?
1 <= piles[i] <= 10^9
.To solve this problem efficiently, a binary search approach is suitable because the possible values of k
(bananas per hour) lie in a range that can be systematically narrowed down.
1
banana per hour.max(piles)
.k
.k
to check if Koko can finish all bananas in h
hours.k
that allows Koko to finish all bananas in h
hours.public class Solution {
public int minEatingSpeed(int[] piles, int h) {
int left = 1;
int right = getMax(piles);
while (left < right) {
int mid = left + (left + right) / 2;
if (canFinish(piles, h, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private int getMax(int[] piles) {
int max = 0;
for (int pile : piles) {
if (pile > max) {
max = pile;
}
}
return max;
}
private boolean canFinish(int[] piles, int h, int k) {
int hours = 0;
for (int pile : piles) {
hours += Math.ceil((double)pile / k);
}
return hours <= h;
}
}
getMax
Function: Determines the maximum pile size, which is the upper limit for our binary search.canFinish
Function: Checks if it’s possible to eat all the bananas with a given eating speed k
in h
hours.max(piles)
is the maximum number of bananas in any pile.n
is the number of piles.This solution efficiently finds the minimum k
by leveraging binary search over the possible range of eating speeds and checking feasibility in linear time for each candidate speed.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?