目录
题目描述:
给你一个整数数组 prices
,其中 prices[i]
表示某支股票第 i
天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
题解:贪心算法
class Solution:
def maxProfit(self, prices: List[int]) -> int:
status = 0
money = 0
l = len(prices)
# 注意是l-1,避免后面prices[i+1]溢出
for i in range(l - 1):
if prices[i + 1] > prices[i] and status == 0:
buy_point = i
status = 1
elif prices[i+1] < prices[i] and status == 1:
cur_earning = prices[i] - prices[buy_point]
money += cur_earning
status = 0
# 兼容最后价格一直是上升的,没有下降的情况,eg:[7,1,2,5,3,6,8]
if status == 1:
return money + prices[l-1] - prices[buy_point]
return money
55. 跳跃游戏
题目描述:
给你一个非负整数数组 nums
,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个下标,如果可以,返回 true
;否则,返回 false
。
题解:贪心
class Solution:
def canJump(self, nums: List[int]) -> bool:
l = len(nums)
start, cover = 0, 0
if l < 2:
return True
# 关键在于start <= cover,start只可以在cover内的范围
while start <= cover:
cover = max(start + nums[start], cover)
if cover >= len(nums) - 1:
return True
start += 1
return 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]
。
题解:贪心
class Solution:
def jump(self, nums: List[int]) -> int:
cur_cover, next_cover = 0, 0
l = len(nums)
ans = 0
if l == 1:
return 0
for i in range(l):
next_cover = max(i + nums[i], next_cover)
if i == cur_cover:
ans += 1
cur_cover = next_cover
if cur_cover >= l - 1:
break
return ans