iq.lab
Python starts when a code cell comes near or you run one
mediumBinary search target 25 min

Koko eating bananas

Koko has piles of bananas: pile i holds piles[i] bananas, and she has h hours to clear them all. Before she starts, she fixes a whole-number speed k: the most bananas she eats in one hour.

An hour belongs to one pile. During it she eats k bananas from that pile, or whatever is left of it if that is fewer than k. If the pile runs out early, the rest of the hour goes unused: she starts the next pile only in the next hour. So a pile of 7 at speed 3 takes three hours: 3, then 3, then 1.

Return the slowest speed k at which she clears every pile within h hours.

Example 1
Inputpiles = [3, 6, 7], h = 6Output3

At speed 3 the piles take 1 + 2 + 3 = 6 hours. At speed 2 they take 2 + 3 + 4 = 9, too many.

Example 2
Inputpiles = [10, 4], h = 2Output10

Two piles in two hours means one hour per pile, so the speed must cover the bigger pile.

Example 3
Inputpiles = [7, 7, 7], h = 20Output2

Speed 1 takes 21 hours, one too many. Speed 2 takes 4 + 4 + 4 = 12.

Constraints
  • 1 ≤ len(piles) ≤ 104

  • len(piles) ≤ h ≤ 109, so some speed always works

  • 1 ≤ piles[i] ≤ 109

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.