接外包,有相关需求的可以联系我:Telegram | Email

Koko Eating Bananas | Binary Search

该文章创建(更新)于02/27/2022,请注意文章的时效性!

文章目录[隐藏]

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

要不赞赏一下?

微信
支付宝
PayPal
Bitcoin

版权声明 | Copyright

除非特别说明,本博客所有作品均采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明转自-
https://www.emperinter.info/2022/02/27/koko-eating-bananas-binary-search/


要不聊聊?

我相信你准备留下的内容是经过思考的!【勾选防爬虫,未勾选无法留言】

*

*



YouTube | B站

微信公众号

优惠码

阿里云国际版20美元
Vultr10美元
搬瓦工 | Bandwagon应该有折扣吧?
Just My SocksJMS9272283 【注意手动复制去跳转】
域名 | namesiloemperinter(1美元)
币安 币安