codejump
MediumPythonJavaScriptTypeScript

Binary Search on the Answer — Koko Eating Bananas

AlgorithmsBinary SearchArrays

Koko has piles of bananas and h hours before the guards return. Each hour
she picks one pile and eats speed bananas from it; if the pile has fewer, she
finishes it and waits for the next hour. Return the minimum integer speed
that lets her eat every banana within h hours.

There is no array to search here: search the answer space. Speeds go from
1 to max(piles), and "can she finish at speed s?" is monotonic: if speed
s works, every faster speed works too. Binary-search the smallest speed that
works, checking each candidate in O(n): O(n log max).

Examples

solve([3, 6, 7, 11], 8)        → 4
solve([30, 11, 23, 4, 20], 5)  → 30
solve([30, 11, 23, 4, 20], 6)  → 23

Constraints

  • 1 <= piles.length <= h <= 10^9
  • 1 <= piles[i] <= 10^9
  • Hours for one pile at speed s = ceil(pile / s).

Sample tests

Test #1The classic example
Input: [[3,6,7,11],8]
Output: 4
Test #2One hour per pile: the largest pile decides
Input: [[30,11,23,4,20],5]
Output: 30
Test #3One spare hour
Input: [[30,11,23,4,20],6]
Output: 23