Koko Eating Bananas

35 min · minEatingSpeed()

Eating twice as fast never takes more time. That one-way relationship turns an enormous range of possible speeds into a search problem.

You're given banana pile sizes in piles and a total of h hours. At an integer speed x bananas per hour, a pile of size p takes ceil(p / x) whole hours, where the ceiling rounds a fraction up to the next integer. Return the smallest positive speed that finishes every pile within h hours.

A few ground rules:

  • Work on only one pile during an hour; spare time from a finished pile isn't carried into another pile.
  • h is at least the number of piles, so a valid speed always exists.
  • The answer must be an integer.

Constraints

  • 1 <= piles.length <= 100_000
  • piles.length <= h <= 1_000_000_000
  • 1 <= piles[i] <= 1_000_000_000

Hints

Write the cost of a speed

For a candidate speed, add ceil(pile / speed) across all piles. The candidate works when that total is at most h.

Find the search bounds

Speed 1 is the slowest candidate worth testing. max(piles) always finishes each pile in one hour, so no faster speed can be minimal.

Use the one-way switch

If a speed works, every faster speed works. If it fails, every slower speed fails. Binary search for the first speed on the working side.

Follow-up

Can your feasibility check stop early once its running hour count already exceeds h?

Visible cases

Examples

Example 1

ready
Input
piles = [
  3,
  6,
  7,
  11
]
h = 8
Expected
4
Why
speed 4 needs 1 + 2 + 2 + 3 = 8 hours

Example 2

ready
Input
piles = [
  30,
  11,
  23,
  4,
  20
]
h = 5
Expected
30
Why
five hours means every pile must finish in one hour

Example 3

ready
Input
piles = [
  9
]
h = 3
Expected
3
Why
one pile of 9 takes exactly three hours at speed 3

Interview signal

Asked at

GoogleAmazonDoorDash
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite