Koko Eating Bananas

LeetCode 875 · View on LeetCode

Binary search on the eating speed. For each candidate speed, calculate total hours needed using ceil(pile / speed). Find the minimum speed that finishes within h hours.

import math

def min_eating_speed(piles: list[int], h: int) -> int:
    lo, hi = 1, max(piles)
    while lo < hi:
        mid = (lo + hi) // 2
        hours = sum(math.ceil(p / mid) for p in piles)
        if hours <= h:
            hi = mid
        else:
            lo = mid + 1
    return lo

if __name__ == '__main__':
    print(min_eating_speed([3, 6, 7, 11], 8))       # 4
    print(min_eating_speed([30, 11, 23, 4, 20], 5))  # 30
    print(min_eating_speed([30, 11, 23, 4, 20], 6))  # 23
© 2026 ByteLearn.dev. Free courses for developers. · Privacy