122.买卖股票的最佳时机II
分析:计算相邻两天的收益,将正收益相加即为总的最大收益
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0
for i in range(len(prices)-1):
if prices[i+1] - prices[i] > 0:
res += prices[i+1] - prices[i]
return res
55. 跳跃游戏
分析:计算覆盖范围,若范围大于最后一个元素的索引,则肯定能成功
class Solution:
def canJump(self, nums: List[int]) -> bool:
cover = 0
for i in range(len(nums)):
if i <= cover:
cover = max(nums[i] + i,cover)
if cover >= len(nums) -1:
return True
return False
45.跳跃游戏II
代码随想录
分析:依然计算覆盖范围,若不能到达最后一个元素,则选取覆盖范围内的最大覆盖范围
class Solution:
def jump(self, nums: List[int]) -> int:
cur_distance = 0
next_distance = 0
res = 0
if len(nums) == 1:
return 0
for i in range(len(nums)):
next_distance = max(i+nums[i],next_distance)
if i == cur_distance:
res += 1
cur_distance = next_distance
if cur_distance >= len(nums) - 1:
return res