32天【程式碼隨想錄演算法訓練營34期】第八章 貪心演算法 part02 (● 122.買賣股票的最佳時機II ● 55. 跳躍遊戲 ● 45.跳躍遊戲II )

MiraMira發表於2024-04-20

122.買賣股票的最佳時機II

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        result = 0
        for i in range(len(prices)-1):
            if prices[i+1] - prices[i] > 0:
                result += prices[i+1] - prices[i]
        return result

55. 跳躍遊戲

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        if len(nums) == 1:
            return True
        cover = 0
        i = 0
        while i <= cover:
            cover = max(nums[i]+i, cover)
            if cover >= len(nums)-1:
                return True
            i += 1
        return False

45.跳躍遊戲II

相關文章