美文网首页
2022-09-20 leetcode 1642 贪心算法用小

2022-09-20 leetcode 1642 贪心算法用小

作者: 木马音响积木 | 来源:发表于2022-09-20 07:40 被阅读0次
    class Solution:
        def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
            #引入小顶堆,里面的值,就是用梯子过这些差距大的,小的,被挤出堆,用砖块过,累加这些砖块,多了,就是不行了。
            from heapq import heappushpop
            he=i=0
            hp =[0]*ladders  #初始化机器,不用判断堆的大小,但是当堆的size 很大时,吃亏
            for x,y in pairwise(heights):
                if x<y:
                    w=y-x
                else:w=0
                if ladders:
                    if w>hp[0]:
                        he+=hp[0]
                        if he > bricks:return i 
                        #这里先判断,及时退出,很重要。
                        heappushpop(hp,w) 
                    else:
                        he+=w 
                        if he>bricks:return i 
                else:#没有梯子的情况
                    he+=w 
                    if he>bricks:return i 
                i+=1
            return i
    

    相关文章

      网友评论

          本文标题:2022-09-20 leetcode 1642 贪心算法用小

          本文链接:https://www.haomeiwen.com/subject/kxdvortx.html