代码随想录算法训练营DAY35|1005.K次取反后最大化的数组和、134. 加油站、135. 分发糖果

1005.K次取反后最大化的数组和

class Solution(object):
    def largestSumAfterKNegations(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        
        nums.sort(key=lambda x: abs(x), reverse=True)
        
        for i in range(len(nums)):
            if nums[i]<0 and k>0:
                nums[i]=-nums[i]
                k -= 1
    
        if k%2==1:
            nums[-1]=-nums[-1]  

        return sum(nums)

134.加油站

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """

        i=0
        count = 0
        result = 0

        used=[0 for j in range(len(gas))]

        for i in range(len(gas)*2):
            if count+gas[i%len(gas)]>=cost[i%len(gas)]:
                count += gas[i%len(gas)]-cost[i%len(gas)]
                if not used[i%len(gas)]:
                    used[i%len(gas)]=1
                elif result == i%len(gas):
                    return result
            elif count+gas[i%len(gas)]<cost[i%len(gas)]:
                count = 0
                result = i+1
            
        return -1            
class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """

        curSum=0
        totalSum=0
        start=0

        for i in range(len(gas)):
            curSum += gas[i]-cost[i]
            totalSum += gas[i]-cost[i]

            if curSum<0:
                curSum=0
                start=i+1
        
        if totalSum<0:
            return -1

        return start

135. 分发糖果

class Solution(object):
    def candy(self, ratings):
        """
        :type ratings: List[int]
        :rtype: int
        """
        candys = [1 for i in range(len(ratings))]

        for j in range(1, len(ratings)):
            if ratings[j]>ratings[j-1]:
                candys[j]=candys[j-1]+1

        for k in range(len(ratings)-2 , -1, -1):
            if ratings[k]>ratings[k+1]:
                candys[k]=max(candys[k+1]+1, candys[k])

        return sum(candys)
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值