Koko Eating Bananas
MediumBinary search on the answer (eating speed)
Guess an eating speed; if she finishes in time try slower, otherwise faster — narrow to the slowest speed that works.
The idea
The eating speed is monotonic: faster always finishes at least as soon. Binary search the smallest speed for which the total hours fit within h.
1
2
3
4
5
6
7
8
9
10
11
0
1
2
3
4
5
6
7
8
9
10
candidates11
Step 1 of 6. Brute force: try every eating speed from 1 up until Koko finishes within 8 hours. Values: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11. candidates 11.
1/6
Brute force
timeO(max·n)spaceO(1)
Try every speed.
1let best = -1;2for (let k = 1; k <= maxPile && best < 0; k++)3 if (hoursNeeded(k) <= h) best = k;4return best;Input
- array
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Memory
- try
- —
- candidates
- 11
- speed
- —
Output
- speed
- —
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- piles = [3, 6, 7, 11], h = 8
- Output:
- 4
- Explanation:
- Eating 4 bananas/hour finishes in time.
Example 2
- Input:
- piles = [30, 11, 23, 4, 20], h = 5
- Output:
- 30
- Explanation:
- She must eat 30/hour to finish in 5 hours.
Example 3
- Input:
- piles = [30, 11, 23, 4, 20], h = 6
- Output:
- 23
- Explanation:
- One extra hour lets her slow to 23/hour.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.