Koko Eating Bananas

Medium· binary search on answer

Problem

There are several piles of bananas and Koko has h hours before the guards return. Each hour she picks one pile and eats up to k bananas from it; if the pile has fewer, she finishes it and waits out the hour. Find the smallest integer speed k that lets her clear every pile within h hours.

Examples

Input: piles = [3,6,7,11], h = 8
Output: 4
At speed 4 the piles take 1 + 2 + 2 + 3 = 8 hours; speed 3 would need 10.
Input: piles = [30,11,23,4,20], h = 6
Output: 23

Constraints

  • • 1 <= piles.length <= 10^4
  • • piles.length <= h <= 10^9
  • • 1 <= piles[i] <= 10^9

Hints & approach

Hint 1

If Koko can finish at speed k, can she also finish at speed k + 1?

Hint 2

The feasible speeds form a contiguous range, so binary search on k itself.

Hint 3

For a given k, the hours needed are the sum of ceil(pile / k).

Approachtry the hints first

Instead of searching an array, binary search over possible answers. Speeds range from 1 to max(piles), and feasibility is monotonic: any speed above a working speed also works. For a candidate k, compute total hours as the sum of ceil(p / k) over all piles (use (p + k - 1) / k with integers). If that fits in h, try slower speeds (hi = k); otherwise go faster (lo = k + 1). The loop converges on the minimum feasible speed.

Time O(n log m), m = max pile · Space O(1)

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.