Practice · Binary search · 4 of 5

Slowest Speed That Finishes in Time

There are some piles of bananas, piles[i] in pile i, and you have h hours to eat them all. You choose a whole-number speed s (bananas per hour) and keep to it. Each hour, you pick one pile and eat s bananas from it; if that pile has fewer than s left, you finish it and rest for the remainder of the hour.

So pile i takes ⌈piles[i] / s⌉ hours (the division rounded up). Return the smallest speed s that finishes every pile within h hours.

Example 1

Input
piles = [4, 9, 6], h = 6
Output
4
At 4 an hour the piles take 1, 3 and 2 hours: 6 in all. At 3 an hour they would take 2 + 3 + 2 = 7.

Example 2

Input
piles = [10, 10], h = 2
Output
10
With one hour for each pile, each pile has to go in a single hour.

Constraints

  • piles holds 1 to 10⁴ numbers.
  • Every pile holds 1 to 10⁹ bananas.
  • piles.length ≤ h ≤ 10⁹, so some speed always works.