本题解法很巧妙,大家可以看题思考一下,在看题解。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
result = 0
for i in range(1, len(prices)):
result += max(prices[i] - prices[i - 1], 0)
return result
本题问能否跳到终点位置,本题如果没接触过,很难想到,所以不要自己憋时间太久,读题思考一会,没思路立刻看题解?
不看具体跳几步,看覆盖范围,不用纠结跳几步
class Solution:
def canJump(self, nums: List[int]) -> bool:
cover = 0
if len(nums) == 1: return True
i = 0
# python不支持动态修改for循环中变量,使用while循环代替
while i <= cover:
cover = max(i + nums[i], cover)
if cover >= len(nums) - 1: return True
i += 1
return False
class Solution:
def jump(self, nums: List[int]) -> int:
if len(nums) == 1:
return 0
cur_distance = 0 # 当前覆盖最远距离下标
ans = 0 # 记录走的最大步数
next_distance = 0 # 下一步覆盖最远距离下标
for i in range(len(nums)):
next_distance = max(nums[i] + i, next_distance) # 更新下一步覆盖最远距离下标
if i == cur_distance: # 遇到当前覆盖最远距离下标
ans += 1 # 需要走下一步
cur_distance = next_distance # 更新当前覆盖最远距离下标(相当于加油了)
#当前覆盖最远距离达到数组末尾,不用再做ans++操作,直接结束
if next_distance >= len(nums) - 1:
break
return ans