188. 股票买卖问题(交易次数为任意正整数)

题目

188. 股票买卖问题(交易次数为任意正整数)_第1张图片

题解

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        N = len(prices)
        # 定义状态:dp[i][j][k]表示在第i天,有j次交易机会,持有或不持有的最大利润
        dp = [[[0 for i in range(2)] for j in range(k+1)] for m in range(N)]

        for i in range(N):
            for j in range(1, k+1):
                if i - 1 == -1:
                    dp[i][j][0] = 0
                    dp[i][j][1] = -prices[i]
                else:
                    dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1] + prices[i])
                    dp[i][j][1] = max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i])

        return dp[N-1][k][0]

你可能感兴趣的:(LeetCode,算法,动态规划,leetcode,笔记)