代码随性训练营第五十一天(Python)| 309.最佳买卖股票时机含冷冻期、714.买卖股票的最佳时机含手续费

发布时间 2023-12-01 15:24:57作者: 忆象峰飞

309.最佳买卖股票时机含冷冻期

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # dp[i][0] 持有股票
        # dp[i][1] 卖出股票那一天
        # dp[i][2] 冷冻期
        # dp[i][3] 保持卖出股票的状态
        dp = [[0] * 4 for _ in range(len(prices))]

        # 初始化
        dp[0][0] =  -prices[0]
        
        for i in range(1, len(prices)):
            dp[i][0] = max(dp[i-1][0], max(dp[i-1][2] - prices[i], dp[i-1][3] - prices[i]))
            dp[i][1] = dp[i-1][0] + prices[i]
            dp[i][2] = dp[i-1][1]
            dp[i][3] = max(dp[i-1][3], dp[i-1][2])
        
        return max(dp[-1][1], dp[-1][2], dp[-1][3])

714.买卖股票的最佳时机含手续费

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        # dp[i][0] 持有股票
        # dp[i][1] 卖出股票
        dp = [[0] * 2 for _ in range(len(prices))]
        dp[0][0] = -prices[0]
        for i in range(1, len(prices)):
            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] - fee)
        return dp[-1][1]