Code Logo

Koko Eating Bananas

Published at24 Jul 2026
Medium 0 views
Like0

Koko loves to eat bananas. There are N piles of bananas, and the i-th pile has piles[i] bananas. The guards will return in h hours. Koko can decide her bananas-per-hour eating speed k. Each hour she chooses a pile and eats up to k bananas from it. If the pile has fewer than k bananas, she eats all of them and cannot continue to another pile that hour. Find the minimum integer k that allows Koko to eat all bananas within h hours.

This is a classic binary search on answer problem. The minimum possible speed is 1 (one banana per hour). The maximum is the largest pile (eating the biggest pile in one hour). Binary search across this range to find the smallest feasible speed.

Feasibility is determined by simulating the eating process at a given speed k. For each pile, compute the hours needed: ceil(pile / k). Sum the hours across all piles and check if the total is at most h. The ceiling division (pile + k - 1) / k avoids floating point.

Edge cases include h equal to the number of piles (speed must be at least max(piles)), very large piles requiring careful integer math, and h being larger than the number of piles allowing slower speeds.

Example Input & Output

Example 1
Input
[30,11,23,4,20], 5
Output
30
Explanation

5 hours means speed must equal max pile (30).

Example 2
Input
[3,6,7,11], 8
Output
4
Explanation

Speed 4 eats all in 8 hours.

Example 3
Input
[312884470], 312884469
Output
2
Explanation

Large pile, barely enough hours.

Example 4
Input
[1,1,1,1], 4
Output
1
Explanation

Four piles in four hours, speed 1 works.

Example 5
Input
[30,11,23,4,20], 6
Output
23
Explanation

Speed 23 finishes in 6 hours.

Algorithm Flow

Recommendation Algorithm Flow for Koko Eating Bananas
Recommendation Algorithm Flow for Koko Eating Bananas

Solution Approach

Binary search speed between 1 and max(piles). Feasibility: sum ceil(pile/k) for each pile, check if <= h.

function solution(piles, h) {
  var lo = 1, hi = 0;
  for (var i = 0; i < piles.length; i++) {
    if (piles[i] > hi) hi = piles[i];
  }
  function canEat(k) {
    var hours = 0;
    for (var i = 0; i < piles.length; i++) {
      hours += Math.floor((piles[i] + k - 1) / k);
    }
    return hours <= h;
  }
  while (lo < hi) {
    var mid = Math.floor((lo + hi) / 2);
    if (canEat(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}

Time O(n log M), Space O(1).

Best Answers

java
class Solution {
    public int solution(int[] piles, int h) {
        int lo = 1, hi = 0;
        for (int p : piles) if (p > hi) hi = p;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (can(piles, mid, h)) hi = mid;
            else lo = mid + 1;
        }
        return lo;
    }
    private boolean can(int[] p, int k, int h) {
        int hours = 0;
        for (int v : p) hours += (v + k - 1) / k;
        return hours <= h;
    }
}