122. 买卖股票的最佳时机 II:
代码思路
prices = [7,1,5,3,6,4],相邻两个元素只要是大于0,把大于0价差加起来就ok。因为只是问利润,但这并不是具体买卖过程。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1, len(prices)):
diff = prices[i] - prices[i-1]
if diff > 0:
profit += diff
return profit
55. 跳跃游戏:
代码思路
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_dist = 0
for i in range(len(nums)):
move = i + nums[i]
if move > max_dist:
max_dist = move
if max_dist >= len(nums) - 1:
return True
if nums[i] == 0 and max_dist == i:
return False
return False
45. 跳跃游戏 II:
代码思路
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
maxPos, end, step = 0, 0, 0
for i in range(n - 1):
if maxPos >= i:
maxPos = max(maxPos, i + nums[i])
if i == end:
end = maxPos
step += 1
return step