SDE & MLE Prep

875. Koko Eating Bananas

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