代码随想录刷题第三十四天
K次取反后最大化的数组和 (LC 1005)
题目思路:
代码实现:
class Solution:def largestSumAfterKNegations(self, nums: List[int], k: int) -> 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-=1if k%2==1:nums[-1] = -nums[-1]result = sum(nums)return result
加油站 (LC 134)
题目思路:
代码实现:
class Solution:def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:curSum = 0totalSum = 0start = 0for i in range(len(gas)):curSum+=gas[i]-cost[i]totalSum+=gas[i]-cost[i]if curSum<0:curSum=0start=i+1if totalSum<0:return -1return start
分发糖果 (LC 135)
题目思路:
代码实现:
class Solution:def candy(self, ratings: List[int]) -> int:candy0 = [0 for _ in range(len(ratings))]candy1 = [0 for _ in range(len(ratings))]candy0[0] = 1candy1[len(ratings)-1] = 1for i in range(1,len(ratings)):if ratings[i] > ratings[i-1]:candy0[i] = candy0[i-1]+1else:candy0[i] = 1for i in range(len(ratings)-2, -1, -1):if ratings[i] > ratings[i+1]:candy1[i] = candy1[i+1]+1else:candy1[i] = 1sum1 = 0for i in range(len(candy0)):sum1+=max(candy0[i], candy1[i])return sum1