代码随想录算法训练营第32天|122.买卖股票的最佳时机II 55. 跳跃游戏 45.跳跃游戏II

122.买卖股票的最佳时机II 

代码随想录

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        #set up result
        res=0
        #set up current price
        cur=prices[0]
        #loop for prices
        for i in range(1,len(prices)):
            #if price is lower than current price, we buy 
            if prices[i]<cur:
                cur=prices[i]
            #if price is higher than current price, we sell and update current 
            #price
            elif prices[i]>cur:
                res+=prices[i]
                res-=cur
                cur=prices[i]
        return res

55. 跳跃游戏

代码随想录

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        #set up arrival place
        arrival=0
        #if only one element, return true
        if len(nums)==1:return True
        #loop for nums
        for i in range(len(nums)):
            #if i <= arrival,we can use the new element as our next step
            #update the new arrival we can reach 
            if i <= arrival:
                arrival=max(arrival,i+nums[i])
                #if arrival is greater than nums length means we arrival goal
                if arrival>=len(nums)-1:
                    return True
        #else return false
        return False

45.跳跃游戏II 

代码随想录

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==1: return 0
        #set up cur nxt and result
        cur=0
        nxt=0
        step=0
        #loop nums, i means where we reach right now
        for i in range(len(nums)-1):
            #nxt is the nxt step max area we can cover
            nxt=max(nxt,i+nums[i])
            #if i reach cur which is the max area we can cover within current   
            #step, we need a new step
            if i==cur:
                step+=1
                cur=nxt
        return step

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值