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

文章包含三个编程问题的解决方案:1)给定一个数组和K次取反操作,如何最大化数组和;2)在加油站的路径规划问题,判断汽车能否完成一圈;3)分发糖果问题,确保评价高的人至少获得的糖果数不少于评价低的人。每个问题都涉及数组处理和优化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

代码随想录

class Solution(object):
    def largestSumAfterKNegations(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        index=0
        #flip the samllest index every time
        for i in range(k):
            #find the smallest index
            for j in range(len(nums)):
                if nums[j]<=nums[index]:
                    index=j
            nums[index]=-nums[index]
        return sum(nums)

134. 加油站 

代码随想录

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        #start_index
        start = 0
        #current sum of gas
        curSum = 0
        #total sum of gas
        totalSum = 0
        for i in range(len(gas)):
            curSum += gas[i] - cost[i]
            totalSum += gas[i] - cost[i]
            #if current usm of gas is smaller than 0, use next stop as start. 
            if curSum < 0:
                curSum = 0
                start = i + 1
        #if total sum of gas is smaller than 0, the car must not reach goal 
        if totalSum < 0: return -1
        #else we can return the result
        return start

135. 分发糖果 

代码随想录


 

class Solution(object):
    def candy(self, ratings):
        """
        :type ratings: List[int]
        :rtype: int
        """
        #candy to give
        candyVec = [1] * len(ratings)
        #loop from left
        for i in range(1, len(ratings)):
            #if ranking of right is higher, give one more candy 
            if ratings[i] > ratings[i - 1]:
                candyVec[i] = candyVec[i - 1] + 1
        #loop from right
        for j in range(len(ratings) - 2, -1, -1):
            #if ranking of left is higher, give one more candy 
            if ratings[j] > ratings[j + 1]:
                candyVec[j] = max(candyVec[j], candyVec[j + 1] + 1)
        #we have a complete result
        return sum(candyVec)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值