All problems

Koko Eating Bananas

Medium · binary search

You have piles, a list where piles[i] is the number of bananas in the i-th pile, and you have h hours before the guards come back. You pick one eating speed k (bananas per hour) and keep it for the whole time.

Each hour you choose one pile and eat up to k bananas from it. If the pile has fewer than k bananas, you finish it and waste the rest of that hour: you do not move on to another pile until the next hour. Return the smallest integer k that lets you eat every banana within h hours.

Examples

Example 1

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

Output: 4

At k = 4 the piles take 1 + 2 + 2 + 3 = 8 hours. At k = 3 they take 1 + 2 + 3 + 4 = 10 hours, which is too slow.

Example 2

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

Output: 30

You have exactly one hour per pile, so you must clear the biggest pile in one hour.

Example 3

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

Output: 23

Constraints