☰ All problems

Koko Eating Bananas

MediumArrayBinary Search

Koko, a gorilla at a wildlife sanctuary, gets her daily bananas in piles: pile i holds piles[i] bananas. The keepers have h hours before the enclosure has to be cleared. Eating too quickly upsets Koko's stomach, so they want the slowest steady pace that still gets every banana eaten in time.

A pace is a whole number k of bananas per hour. Each hour, Koko picks one pile and eats k bananas from it. If that pile has fewer than k left, she finishes it and rests for the rest of the hour rather than starting on another pile.

Return the smallest pace k that finishes all the piles within h hours. Every test allows at least one hour per pile, so some pace always works.

Example 1
Input: piles = [10,3,7], h = 6
Output: 4

Explanation: At 4 bananas per hour the piles take 3 + 1 + 2 = 6 hours. At 3 per hour they would take 4 + 1 + 3 = 8, which is too long.

Example 2
Input: piles = [9,15], h = 2
Output: 15

Explanation: With exactly one hour per pile, Koko has to finish the biggest pile in a single hour.

Example 3
Input: piles = [1,1,1], h = 100
Output: 1

Explanation: Even the slowest possible pace finishes in 3 hours.

Constraints

  • There are between 1 and 10^4 piles.
  • Each pile holds between 1 and 10^9 bananas.
  • h is at least the number of piles and at most 10^9.
💡 Hint 1

For a fixed speed k, the time for one pile is ceil(pile / k), so checking a single speed takes O(n).

💡 Hint 2

If speed k is fast enough, every faster speed is too. That monotonic yes/no answer can be binary searched.

💡 Hint 3

The answer lies between 1 and max(piles). Watch out for overflow when adding up hours in Java.

/**
 * @param {number[]} piles
 * @param {number} h
 * @return {number}
 */
function minEatingSpeed(piles, h) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc