Koko Eating Bananas | Binary Search

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.

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))
``````

### 要不赞赏一下?

 微信 支付宝 PayPal Bitcoin

``https://www.emperinter.info/2022/02/27/koko-eating-bananas-binary-search/``

 阿里云国际版 20美元 Vultr 10美元 搬瓦工 | Bandwagon 应该有折扣吧？ Just My Socks JMS9272283 【注意手动复制去跳转】 域名 | namesilo `emperinter`(1美元) 币安 币安