Koko loves to eat bananas. There are n
piles of bananas, the i-th
pile has piles[i]
bananas. The guards have gone and will come back in h
hours.
Koko can decide her bananas-per-hour eating speed of k
. Each hour, she chooses some pile of bananas and eats k
bananas from that pile. If the pile has less than k
bananas, she eats all of them instead and will not eat any more bananas during that hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k
such that she can eat all the bananas within h
hours.
Example:
Input: piles = [3,6,7,11], h = 8
Output: 4
Constraints:
1 <= piles.length <= 10^4
piles.length <= h <= 10^9
1 <= piles[i] <= 10^9
k
is so large that Koko finishes a pile in less than an hour?
k
is larger than the pile’s size, she finishes the pile and waits until the next hour to start a new pile.k
:
k
can be 1
(eating 1 banana per hour).k
can be the largest pile size (max(piles)
) because if Koko eats all bananas from the largest pile in one hour, she will definitely have time for the rest.k
that allows Koko to eat all bananas within h
hours.h
.k
, calculate the total hours required:
(pile size // k)
rounded up.h
, adjust the range to search for a smaller k
.k
.from math import ceil
def minEatingSpeed(piles, h):
def canEatAllBananas(k):
total_hours = 0
for pile in piles:
total_hours += ceil(pile / k)
return total_hours <= h
left, right = 1, max(piles)
while left < right:
mid = (left + right) // 2
if canEatAllBananas(mid):
right = mid
else:
left = mid + 1
return left
O(log(max(piles)))
because we are halving the search range each time.O(n)
time, where n
is the number of piles.Overall time complexity: O(n * log(max(piles)))
.
This complexity should be efficient enough given the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?