代码随想训练营第三十四天(Python)| 1005.K次取反后最大化的数组和、134. 加油站、135. 分发糖果
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] *= -1
k -= 1
if k % 2 == 1:
nums[-1] *= -1
return sum(nums)
134. 加油站
1、暴力法
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
for i in range(len(gas)):
rest = gas[i] - cost[i] # 剩余汽油量
index = (i + 1) % len(gas) # 到达第几个加油站
# 从第 i 个汽油站出发
while rest > 0 and index != i:
rest += gas[index] - cost[index]
index = (index + 1) % len(gas)
# 跑完一圈且汽油量大于等于0:
if rest >= 0 and index == i:
return i
return -1
2、贪心法
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
cur_gas = 0
total_gas = 0
start = 0
for i in range(len(gas)):
cur_gas += gas[i] - cost[i]
total_gas += gas[i] - cost[i]
if cur_gas < 0:
start = i + 1
cur_gas = 0
if total_gas < 0:
return -1
return start
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
res = [1] * n
# 从左到右遍历
for i in range(1, n):
if ratings[i] > ratings[i-1]:
res[i] = res[i-1] + 1
# 从右到左遍历
for j in range(n-2, -1, -1):
if ratings[j] > ratings[j+1]:
res[j] = max(res[j], res[j+1] + 1)
return sum(res)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?