Skip to main content

Koko Eating Bananas

MediumPremium

A monkey named Koko enjoys eating bananas. She is presented with n piles of bananas, where the i-th pile contains piles[i] bananas. Koko can eat at a constant speed of k bananas per hour. In each hour, she can pick one pile and eat up to k bananas from it. If the pile has fewer than k bananas, she eats the entire pile and waits for the next hour to pick another.

She wants to finish eating all the bananas within h hours before the guards arrive.

Your task is to determine the minimum integer value of k that allows her to finish all the bananas within the given time.

Example 1

Input: piles = [30, 11, 23, 4, 20], h = 6 Output: 23

To determine how long it would take Koko to eat all the bananas at this speed, we calculate the time for each pile as the ceiling of pile_size / k since she can’t eat a partial pile in less than an hour.

For pile 30, it would take ⌈30 / 23⌉ = 2 hours.

For pile 11, it's ⌈11 / 23⌉ = 1 hour.

For pile 23, it's ⌈23 / 23⌉ = 1 hour.

For pile 4, it's ⌈4 / 23⌉ = 1 hour.

For pile 20, it's ⌈20 / 23⌉ = 1 hour.

Summing these up: 2 + 1 + 1 + 1 + 1 = 6 hours in total.

Example 2

Input: piles = [3, 6, 7, 11], h = 4 Output: 11

She has exactly 4 hours for 4 piles. So each pile must be finished in one hour, meaning speed must be at least the size of the largest pile → max(piles) = 11.