Description
Choose the smallest positive integer eating speed that finishes every banana pile within h hours. Each hour handles only one pile; leftovers in that hour cannot be spent on another pile. Assume h is at least the pile count.
Solution
def min_eating_speed(piles, h):
left, right = 1, max(piles)
while left < right:
middle = (left + right) // 2
hours = sum((pile + middle - 1) // middle for pile in piles)
if hours <= h:
right = middle
else:
left = middle + 1
return leftExamples
Example 1
- Input
[[3,6,7,11],8]- Output
4
Speed 4 requires 1 + 2 + 2 + 3 hours.
Example 2
- Input
[[30,11,23,4,20],5]- Output
30
Each pile must fit in one hour.
Example 3
- Input
[[1,1],3]- Output
1
The smallest possible speed suffices.
Approach
Binary-search speeds between 1 and the largest pile. For each speed, sum ceiling(pile / speed) hours. Feasible speeds form a suffix, so move toward the first feasible speed.
Time & space
O(n log M) time and O(1) auxiliary space, where n is the number of piles and M is the largest pile.