代码随想训练营第三十二天(Python)| 122.买卖股票的最佳时机 II、55. 跳跃游戏、45.跳跃游戏 II

发布时间 2023-11-13 16:07:18作者: 忆象峰飞

122.买卖股票的最佳时机 II
1、贪心

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

2、动态规划

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        # 第一列代表第几天,第二列代表是否持有股票
        dp = [[0] * 2 for _ in range(n)]
        # 0 代表持有股票, 1 代表不持有股票
        dp[0][0] = -prices[0]
        dp[0][1] = 0
        for i in range(1, n):
            dp[i][0] = max(dp[i-1][0], dp[i-1][1]-prices[i])
            dp[i][1] = max(dp[i-1][1], dp[i-1][0]+prices[i])
        return dp[-1][1]

55. 跳跃游戏

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        cover = 0 # 每个位置可以覆盖的范围
        n = len(nums)
        if n == 1:
            return True
        for i in range(n):
            if i <= cover:
                cover = max(cover, nums[i]+i)
                if cover >= n-1:
                    return True
        return False

45.跳跃游戏 II
1、走一步看一步

class Solution:
    def jump(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 1:
            return 0

        cur_distance = 0 # 当前覆盖的最远距离
        res = 0 # 移动的步数
        next_distance = 0 # 下一步覆盖的最远距离
        for i in range(n):
            next_distance = max(nums[i]+i, next_distance)
            if i == cur_distance:
                res += 1 # 需要移动下一步
                cur_distance = next_distance # 更新当前可以移动的最远距离
                if next_distance >= n - 1:   
                    break
        return res

2、动态规划

class Solution:
    def jump(self, nums: List[int]) -> int:
        n = len(nums)
        # 初始化数组, 每个位置需要多少步到
        dp = [10**4+1] * n
        dp[0] = 0

        for i in range(n): # 遍历数组
            for j in range(nums[i]+1): # 遍历覆盖范围
                if i + j < n: # 避免走出数组范围
                    dp[i+j] = min(dp[i+j], dp[i]+1)
        return dp[-1]