122.买卖股票的最佳时机II
解题思路:(贪心)
计算每天的收益,将每天的正收益加起来得到最大利润,局部最优得到全局最优
class Solution:
def maxProfit(self, prices: List[int]) -> int:
prof = 0
for i in range(1,len(prices)):
prof += max(0,prices[i] - prices[i-1])
return prof
55. 跳跃游戏
解题思路:(贪心)
选每次能cover最大范围的,推出全局最优
class Solution:
def canJump(self, nums: List[int]) -> bool:
cover = 0
i = 0
while i <= cover:
cover = max(i+nums[i],cover)
if cover >= len(nums)-1: return True
i += 1
return False
45.跳跃游戏II
解题思路:(贪心)
class Solution:
def jump(self, nums: List[int]) -> int:
cur = 0
nxt = 0
res = 0
for i in range(len(nums)):
nxt = max(i+nums[i],nxt)
if i == cur:
if cur < len(nums)-1:
res += 1
cur = nxt
if cur >= len(nums) - 1:
break
else: break
return res