PracticeNeetCode ↗LeetCode ↗
Koko has n piles of bananas and h hours before the guards return. Each hour she picks one pile and eats up to k bananas from it — if a pile has fewer than k, she finishes that pile and stops early for the hour. Find the minimum integer eating speed k such that she finishes every pile within h hours.
left = 1, right = max(piles) — the smallest and largest speeds worth ever trying.mid, then total hours needed at that speed.h, mid is fast enough — try a slower speed by pulling right down to mid.mid is too slow — push left up past it.Time: O(n · log(max(piles))) — Space: O(1)
import math
def minEatingSpeed(piles: list[int], h: int) -> int:
left, right = 1, max(piles)
while left < right:
mid = left + (right - left) // 2
hours = sum(math.ceil(pile / mid) for pile in piles)
if hours <= h:
right = mid
else:
left = mid + 1
return leftHow the solution above works, piece by piece.
max(piles) (at that speed every pile takes exactly one hour).mid, ceil(pile / mid) is the hours for one pile; sum them for the total.h, mid works but a slower speed might too: right = mid (keep mid).left = mid + 1.left == right that's the slowest speed that works. O(n log max) time: each of the log(max) probes sums n piles.Running it on piles = [3, 6, 7, 11], h = 8: