Koko Eating Bananas
MediumNeetCode 150 Binary SearchoyoTrexquantNokiaRippleTuringDoorDashProblem
Koko has several piles of bananas, piles[i] in pile i. She picks a speed
k: each hour she chooses one pile and eats up to k bananas from it. If the pile has fewer
than k, she finishes it and waits out the rest of that hour.
She must finish every pile within h hours. Return the smallest whole number k that works.
Constraints
- 1 ≤ piles.length ≤ 10⁴
- piles.length ≤ h ≤ 10⁹
- 1 ≤ piles[i] ≤ 10⁹
Examples: pick one to animate
Solutions
TimeO(n log m)
SpaceO(1)
Time: The speed range 1 to m (the biggest pile) is halved each round, about log2(m) rounds, and each round adds up hours over n piles.
Space: Only lo, hi, mid and the hour total are stored.
If speed k finishes in time, any faster speed does too, so feasibility is monotonic. Binary search the
smallest working speed: count hours as the sum of ceil(pile / k). If hours ≤ h then hi = mid, else lo = mid + 1.