本文主要是介绍代码随想录算法训练营DAY32|122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
122.买卖股票的最佳时机II
- 题目链接:122.买卖股票的最佳时机II
class Solution(object):def maxProfit(self, prices):""":type prices: List[int]:rtype: int"""max_profit = 0profit = 0buyin_idx = 0for i in range(len(prices)):print(buyin_idx)if prices[i]< prices[buyin_idx]:buyin_idx=iif prices[i]-prices[buyin_idx]>profit and i<len(prices)-1:profit=prices[i]-prices[buyin_idx]elif prices[i]-prices[buyin_idx]>profit and i==len(prices)-1:profit=prices[i]-prices[buyin_idx]max_profit+=profitelse:max_profit+=profitprofit=0buyin_idx=ireturn max_profit
class Solution(object):def maxProfit(self, prices):""":type prices: List[int]:rtype: int"""max_profit = 0for i in range(1, len(prices)):if prices[i]-prices[i-1]>0:max_profit+=prices[i]-prices[i-1]return max_profit
55.跳跃游戏
- 题目链接:55.跳跃游戏
- 注意这里是while i<=cover
class Solution(object):def canJump(self, nums):""":type nums: List[int]:rtype: bool"""if len(nums)==1:return Truecover = 0i=0while i<=cover:cover = max(i+nums[i], cover)if cover>=len(nums)-1:return Truei+=1return False
45.跳跃游戏II
- 题目链接:45.跳跃游戏II
- step+1的条件(走不下去了再+1)
class Solution(object):def jump(self, nums):""":type nums: List[int]:rtype: int"""if len(nums)==1:return 0nextdistance=0curdistance=0i=0step=0for i in range(len(nums)):nextdistance=max(i+nums[i], nextdistance)if curdistance>=len(nums)-1:return stepif i==curdistance:curdistance=nextdistancestep+=1return step
这篇关于代码随想录算法训练营DAY32|122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!