Koko Eating Bananas Visualizer & Step-by-Step Algorithm Solution

Binary search on integer speed k in range [1 .. max(piles)] to find the minimum eating speed to finish all piles within h hours.

Category: binary-search | Difficulty: Medium

Tags: Binary Search on Answer, Monotonic Predicate

Koko Eating Bananas

Banana Piles
3
0
6
1
7
2
11
3
L
1
R
11
100%
state
allowed hours (h)8 hrs
left1
right11
minSpeedSearching
Initialization
1/24
Explanation

Start minEatingSpeed with piles = [3, 6, 7, 11] and deadline h = 8 hours.

Source Code
1function minEatingSpeed(piles, h) {
2 let left = 1;
3 let right = Math.max(...piles);
4 let ans = right;
5 while (left <= right) {
6 const mid = Math.floor((left + right) / 2);
7 let hours = 0;
8 for (const p of piles) {
9 hours += Math.ceil(p / mid);
10 }
11 if (hours <= h) {
12 ans = mid;
13 right = mid - 1;
14 } else {
15 left = mid + 1;
16 }
17 }
18 return ans;
19}