An interactive visualization of how binary search finds the minimum eating speed. Watch the algorithm narrow down the search space step by step.
Binary Search LeetCode 875 β Mediumn piles of bananas, the i-th pile has piles[i] bananas.
The guards have gone and will come back in h hours.k (bananas per hour). Each hour, she picks a pile and eats k bananas from it.
If a pile has fewer than k bananas, she eats all of them and won't eat any more that hour.k such that she can eat all the bananas within h hours.
import kotlin.math.ceilfun minEatingSpeed(piles: IntArray, h: Int): Int { var lo = 1 var hi = piles.max() while (lo < hi) { val mid = (lo + hi) / 2 val hours = piles.sumOf { ceil(it.toDouble() / mid).toInt() } if (hours <= h) { // can finish -> try smaller hi = mid } else { // too slow -> need faster lo = mid + 1 } } return lo // minimum valid speed}
The eating speed k has a monotonic property: if Koko can finish at speed k,
she can also finish at any speed greater than k. This makes it a perfect candidate for binary search on the answer.
lo = 1 (minimum possible speed), hi = max(piles) (eating the largest pile in one hour β never need more)mid = (lo + hi) // 2mid β for each pile, it takes βpile / midβ hourshi = midlo = mid + 1
We do log(max(piles)) binary search iterations, and each iteration scans all n piles to compute the total hours.