Koko loves to eat bananas. There are n piles of bananas, the ith 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 this 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.
Solution
Binary Search
Code
- submit code
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
# 在x速度的情况下
# 吃完香蕉需要花费的事件
def f(piles, x):
hours = 0
for i in range(len(piles)):
hours += piles[i] // x
if piles[i] % x > 0:
hours += 1
return hours
# 吃香蕉的速度
# 最小为1
# 最大为piles中的最大值
left = 1
right = max(piles)
while left < right:
mid = (right + left) // 2
if f(piles, mid) <= h:
right = mid
else:
left = mid + 1
return right
- full code
class Solution:
def minEatingSpeed(self, piles, h):
# 在x速度的情况下
# 吃完香蕉需要花费的事件
def f(piles, x):
hours = 0
for i in range(len(piles)):
hours += piles[i] // x
if piles[i] % x > 0:
hours += 1
return hours
# 吃香蕉的速度
# 最小为1
# 最大为piles中的最大值
left = 1
right = max(piles)
while left < right:
mid = (right + left) // 2
if f(piles, mid) <= h:
right = mid
else:
left = mid + 1
return right
piles = [3,6,7,11]
H = 8
S = Solution()
print(S.minEatingSpeed(piles,H))