Minimum Eating Speed to Finish in Time

Problem Given piles[], where piles[i] is the number of bananas in the i-th pile, and h hours available, find the minimum integer eating speed k (bananas per hour) that finishes every pile within h hours. Each hour you pick one pile and eat up to k bananas from it; if the pile has fewer than k left, you finish it and the hour is still used up.

Input / Output

  • Input: an integer array piles[] and an integer h.
  • Output: the smallest integer k such that all piles can be eaten within h hours.

Constraints

  • 1 <= piles.length <= 10^4, piles.length <= h <= 10^9, 1 <= piles[i] <= 10^9.
  • Values reach 10^9, so scanning every candidate speed from 1 upward is far too slow — but checking a single speed is cheap.
  • Because a pile is never shared across hours, hours for one pile at speed k is ceil(piles[i] / k).

Example

  • piles = [3,6,7,11], h = 8 -> 4. At k=4: 1+2+2+3 = 8 hours, exactly fitting. At k=3: 1+2+3+4 = 10 hours, too slow.
  • Tricky case: piles = [30,11,23,4,20], h = 5 -> 30. With exactly as many hours as piles, you get one hour per pile, so k must be the largest pile — the answer is pinned to the upper bound, which catches solutions that set hi too low.
asked …
LeaderboardSalaryAccount