Koko Eating Bananas
1 approach, code in every language
Problem description
You are given a list of banana piles, where the value at each position tells you how many bananas sit in that pile. You also have a deadline of h hours before the piles are taken away. Each hour you pick a single pile and eat up to a fixed speed of k bananas from it; if the pile has fewer than k bananas left you finish it and idle for the rest of that hour, but you never switch to a second pile within the same hour.
Your goal is to find the smallest whole-number speed k that still lets you clear every pile within h hours. Larger speeds always make the job easier, so the answer is the exact point where 'just fast enough' begins.
Example 1
Input: piles = [3,6,7,11], h = 8
Output: 4
At speed 4 the piles take 1 + 2 + 2 + 3 = 8 hours, exactly meeting the deadline. Speed 3 would need 1 + 2 + 3 + 4 = 10 hours, which is too slow.
Example 2
Input: piles = [30,11,23,4,20], h = 5
Output: 30
There are 5 piles and only 5 hours, so each pile must be cleared in a single hour. The speed therefore has to be at least the size of the largest pile, which is 30.
Constraints
1 <= piles.length <= 10^4piles.length <= h <= 10^91 <= piles[i] <= 10^9
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Overnight Print Rate is our own problem on the technique behind Koko Eating Bananas: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free