代码随想录Day32|贪心02

加油站

  • 不是很会这种贪心算法
  • 写一下暴力写法,但是超时了。。。。。
## 暴力算法
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        start = 0
        for i in range(len(gas)):
            index = i
            res = 0
            llen = 0
            while( res>=0 and llen<len(gas) ):
                res += gas[index] - cost[index]
                index = (index+1)%len(gas)
                llen += 1
            if res>=0 and llen==len(gas):
                return i
        return -1
## 贪心算法
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        cur = 0
        total = 0
        flag = 0
        for i in range(len(gas)):
            cur += gas[i]-cost[i]
            total += gas[i]-cost[i]
            if cur < 0:
                flag = i+1
                cur = 0
        if total<0:
            return -1
        return flag

分发糖果

  • 左遍历和右遍历,这个思路也出现在打家劫舍那个环形上
class Solution:
    def candy(self, ratings: List[int]) -> int:
        res = [1]*len(ratings)
        for i in range(1,len(ratings)):
            if ratings[i]>ratings[i-1]:
                res[i] = res[i-1] + 1
 
        for i in range(len(ratings)-2,-1,-1):
            if ratings[i]>ratings[i+1]:
                res[i] = max( res[i], res[i+1] + 1)
        
        return sum(res)

860. 柠檬水找零

  • 简单模拟
class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        dicts = {}
        dicts[5],dicts[10] = 0,0
        for bill in bills:
            if bill == 5:
                dicts[5] += 1
            elif bill == 10:
                dicts[5] -= 1
                dicts[10] += 1
            else:
                if dicts[10]>=1:
                    dicts[10] -= 1
                    dicts[5] -= 1
                else:
                    dicts[5] -= 3
            if dicts[5]<0:
                    return False
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值