Leetcode: 188. Best Time to Buy and Sell Stock IV

Problem Statement

from typing import List


class Solution:
    def maxProfit(self, K: int, prices: List[int]) -> int:
        N = len(prices)
        dp = [[0] * (K + 1) for _ in range(N + 1)]
        best = [[0] * (K + 1) for _ in range(N + 1)]
        for i in range(N, -1, -1):
            for k in range(K, -1, -1):
                if k == 0 or i == N:
                    continue
                dp[i][k] = max(dp[i + 1][k], -prices[i] + best[i + 1][k])
                best[i][k] = max(best[i + 1][k], prices[i] + dp[i + 1][k - 1])
        return dp[0][K]


assert Solution().maxProfit(2, [2, 4, 1]) == 2
assert Solution().maxProfit(2, [3, 2, 6, 5, 0, 3]) == 7