875. Koko Eating Bananas
Asked at 40Amazon75Bloomberg64Microsoft64Google59Meta59Apple22Infosys61Nvidia55Zoho52Trexquant100oyo100Nokia87Ripple82Turing80DoorDash76Adobe74Accenture71Okta71Swiggy69Expedia65Oracle62HashedIn62Autodesk59Flipkart59josh technology58Netflix58Coupang58Agoda57Palo Alto Networks50TikTok50Citadel47Snap45Atlassian42PayPal42tcs42Salesforce41Uber40Goldman Sachs36IBM35LinkedIn27
Problem
Koko eats bananas from piles at k bananas per hour: each hour she picks one pile and eats k from it (or the whole pile if it has fewer, then waits out the hour). Return the minimum integer k that lets her finish everything within h hours.
Example: piles = [3,6,7,11], h = 8 → 4
Constraints: n ≤ h ≤ 10⁹; piles up to 10⁹.
hours(speed) is decreasing in speed → find the smallest speed in [1, max(piles)] with hours ≤ h.
piles [3,6,7,11], h=8
speed: 1 2 3 4 5 ... 11
ok? F F F T T ... T -> 4
Complexity: O(n log max).
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
lo, hi = 1, max(piles)
while lo < hi:
k = (lo + hi) // 2
if sum((p + k - 1) // k for p in piles) <= h:
hi = k
else:
lo = k + 1
return lo
assert Solution().minEatingSpeed([3, 6, 7, 11], 8) == 4
assert Solution().minEatingSpeed([30, 11, 23, 4, 20], 5) == 30
assert Solution().minEatingSpeed([30, 11, 23, 4, 20], 6) == 23
class Solution {
public int minEatingSpeed(int[] piles, int h) {
int lo = 1, hi = 0;
for (int p : piles) hi = Math.max(hi, p);
while (lo < hi) {
int k = lo + (hi - lo) / 2;
long hours = 0;
for (int p : piles) hours += (p + k - 1) / k;
if (hours <= h) hi = k; else lo = k + 1;
}
return lo;
}
}
func minEatingSpeed(piles []int, h int) int {
lo, hi := 1, 0
for _, p := range piles {
hi = max(hi, p)
}
for lo < hi { // smallest speed that finishes in h hours
k := lo + (hi-lo)/2
hours := 0
for _, p := range piles {
hours += (p + k - 1) / k
}
if hours <= h {
hi = k
} else {
lo = k + 1
}
}
return lo
}