代码随想录贪心算法part02| 122.买卖股票的最佳时机II 、55. 跳跃游戏 、45.跳跃游戏II、1005.K次取反后最大化的数组和
122.买卖股票的最佳时机II - 注意动态规划法
思路
:
因为这道题每天都可以买卖,所以一个区间就可以一天一天的进行交易,只要后一天的价格高于前一天的价格,就进行交易,获取利润
python代码
:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(len(prices)-1):
if prices[i+1] - prices[i] > 0:
profit = profit + prices[i+1] - prices[i]
return profit
55. 跳跃游戏
思路打开:不用管是跳几步,看覆盖范围,覆盖范围最终能不能把最后一步覆盖掉;贪心要尽量往大地去扩充覆盖范围
for循环,i小于cover
(动态for循环,但python中不支持,用while代替)
class Solution:
def canJump(self, nums: List[int]) -> bool:
if len(nums) == 1:
return True
cover = 0
cover_max = 0
i = 0
while i <= cover:
cover = max(cover, i + nums[i])
if cover >= len(nums) - 1:
return True
i += 1
return False
# 2025-4-12
class Solution:
def canJump(self, nums: List[int]) -> bool:
cover = nums[0]
i = 0 # 下标id
while i <= cover: # 不是<
cover = max(cover, i + nums[i])
if cover >= len(nums) - 1:
return True
i += 1 # 忘记更新i了,导致超时
return False
45.跳跃游戏II
要求到达最后一步的最小步数
curr和next分别记录当前和下一步最大的覆盖范围
在当前的覆盖范围内进行遍历,同时记录下一步的最大范围,如果遍历到当前的最后一个覆盖范围,判断是否到终点了,否则,result++并更新当前的覆盖范围。
class Solution:
def jump(self, nums: List[int]) -> int:
if not nums:
return 0
curr = 0
next = 0
result = 0
i = 0
while i < len(nums):
next = max(next, i + nums[i])
if i == curr:
if curr != len(nums)-1:
result += 1
curr = next
if next >= len(nums)-1:
break
i += 1
return result
# 2025-4-12
class Solution:
def jump(self, nums: List[int]) -> int:
cur_cover = 0 # 不能初始化为nums[0], 会少算一步
next_cover = 0
res = 0
i = 0
while i <= cur_cover:
next_cover = max(next_cover, i+nums[i])
if i == cur_cover:
if cur_cover != len(nums) - 1:
res += 1
cur_cover = next_cover
if next_cover >= len(nums) - 1:
break
i += 1 # 别总是忘记写啊
return res
class Solution:
def jump(self, nums: List[int]) -> int:
cur_cover = 0
next_cover = 0
res = 0
i = 0
while i < len(nums): # 改,if next_cover >= len(nums) - 1: 可删
next_cover = max(next_cover, i+nums[i])
if i == cur_cover:
if cur_cover != len(nums) - 1:
res += 1
cur_cover = next_cover
# if next_cover >= len(nums) - 1:
# break
i += 1
return res
1005.K次取反后最大化的数组和
简单题,每次选最小的就可以
class Solution:
def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
while k:
k -= 1
min_num = min(nums)
idx = nums.index(min_num)
nums[idx] = -min_num
return sum(nums)