Koko Eating Bananas - Code

Implementation of binary search on the answer.

Here is the implementation:

function minEatingSpeed(piles, h):
    low = 1
    high = max(piles)

    while low < high:
        mid = low + (high - low) / 2
        if canFinish(piles, mid, h):
            high = mid
        else:
            low = mid + 1

    return low

function canFinish(piles, k, h):
    hours = 0
    for pile in piles:
        hours = hours + ceil(pile / k)
    return hours <= h

Pattern recognition: Whenever you see "minimum XX such that condition is satisfied" or "maximum XX such that condition is satisfied," think binary search on the answer.

The answer is lowlow after the loop. Since we use high = mid when valid, we find the smallest valid answer.