今日任务
目录
122.买卖股票的最佳时机II - Medium
题目链接:力扣-122. 买卖股票的最佳时机 II
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
提示:寻找局部极大值和极小值,注意处理端点;买入价可以为0
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
prediff = 0
curdiff = 0
buy = -1
sell = 0
for i in range(len(prices)-1):
curdiff = prices[i+1] - prices[i]
if prediff <=0 and curdiff > 0:
buy = prices[i]
if prediff >0 and curdiff <= 0:
sell = prices[i]
if i == len(prices)-2 and not sell: sell = prices[-1]
if buy >= 0 and sell > 0:
profit += sell - buy
sell = 0
buy = -1
prediff = curdiff
return profit
55. 跳跃游戏 - Medium
题目链接:力扣-55. 跳跃游戏
给定一个非负整数数组
nums
,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
提示:逐步更新每个位置能覆盖的指标范围
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_range = 0
if len(nums) <= 1: return True
i = 0
while i <= max_range:
max_range = max(max_range, i+nums[i])
if max_range >= len(nums)-1: return True
i += 1
return False
45.跳跃游戏II - Medium
题目链接:力扣-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]。
提示:不只考虑当前一步的覆盖范围,同时考虑下一步的覆盖范围
class Solution:
def jump(self, nums: List[int]) -> int:
cur_range = 0
next_range = 0
step = 0
for i in range(len(nums)-1):
next_range = max(next_range, i+nums[i])
if i == cur_range:
step += 1
cur_range = next_range
return step