题目简介
122. 买卖股票的最佳时机 II
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
55. 跳跃游戏
给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false 。
45. 跳跃游戏 II
给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。
每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:
0 <= j <= nums[i]
i + j < n
返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]。
初见思路
122.贪心就好,只要能赚钱就卖出,这样的话算出最大利润即可。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <=1:
return 0
max_profit = 0
for i in range(0,len(prices)-1):
if prices[i+1] > prices[i]:
max_profit += prices[i+1] - prices[i]
return max_profit
- 本题的核心在于右侧的贪心的最大边界是动态的。用一个临时变量把右侧的最大能达到的位置限定起来,然后再做贪心。
class Solution:
def canJump(self, nums: List[int]) -> bool:
right_index = 0
for i in range(len(nums)):
if i <= right_index:
right_index = max(i + nums[i], right_index)
if right_index >= len(nums) - 1:
return True
return False
45.沿袭55题的思路,只不过这次考虑走到最后一位的最小步数。这时我们要考虑,步数最少那么每次步幅最大,限定最右边为每次最大到达位置,当遍历指针到达该位置,说明走了一步,步数+1,按照这个逻辑,我们得到:
class Solution:
def jump(self, nums: List[int]) -> int:
right,max_loc,steps = 0,0,0
for i in range(len(nums)-1):
max_loc = max(max_loc,nums[i]+i)
if i == right:
right = max_loc
steps += 1
return steps
复盘思路
https://programmercarl.com/0055.%E8%B7%B3%E8%B7%83%E6%B8%B8%E6%88%8F.html
https://programmercarl.com/0045.%E8%B7%B3%E8%B7%83%E6%B8%B8%E6%88%8FII.html