代码随想录算法训练营第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:
                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

你可能感兴趣的:(算法,游戏,数据结构)