Skip to content
thesarfo

Reference

Koko Eating Bananas

Binary searching over possible eating speeds to find the minimum that finishes all banana piles within h hours.

views 0

n piles of bananas, Koko eats k bananas/hour from one pile at a time, h hours available. Find the minimum k so Koko finishes everything within h hours. (LeetCode problem)

This is a binary search on the answer problem: instead of searching within an array, we binary search over a range of possible answers (here, possible eating speeds), using a feasibility check to decide which half to keep.

Brute force: try every k from 1 to max(piles), computing the hours needed for each (ceil(pile/k) summed across piles) — slow, gives TLE on large inputs.

Binary search: the answer lies in [1, max(piles)]. For each mid, compute total hours needed; if <= h, it’s a valid (possibly non-minimal) speed, so try slower (high = mid); otherwise try faster (low = mid + 1).

class Solution {
public int minEatingSpeed(int[] piles, int h) {
int max = 0;
for (int p : piles) {
max = Math.max(max, p);
}
int low = 1, high = max;
while (low < high) {
int mid = low + (high - low) / 2;
int totalH = calculateTotalHours(piles, mid);
if (totalH <= h) {
high = mid; // try a slower (smaller) speed
} else {
low = mid + 1; // need to go faster
}
}
return low;
}
public int calculateTotalHours(int[] piles, int hourly) {
int totalH = 0;
for (int i = 0; i < piles.length; i++) {
totalH += Math.ceil((double) piles[i] / (double) hourly);
}
return totalH;
}
}

Time: O(N × log(max(piles))). Space: O(1).