SDE & MLE Prep

188. Best Time to Buy and Sell Stock IV

Problem

prices[i] is a stock's price on day i. Make at most k buy-then-sell transactions (holding at most one share at a time) and return the maximum profit.

Example: k = 2, prices = [3,2,6,5,0,3] → 7

Constraints: k ≤ 100; n ≤ 1000.

Generalize 123 to k transactions: arrays buy[1..k], sell[1..k]; buy[j] = max(buy[j], sell[j−1] − p), sell[j] = max(sell[j], buy[j] + p). If k ≥ n/2 it's unlimited (sum of rises).

Complexity: O(n·k).

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        if k >= len(prices) // 2:
            return sum(max(0, b - a) for a, b in zip(prices, prices[1:]))
        buy = [float("-inf")] * (k + 1)
        sell = [0] * (k + 1)
        for p in prices:
            for j in range(1, k + 1):
                buy[j] = max(buy[j], sell[j - 1] - p)
                sell[j] = max(sell[j], buy[j] + p)
        return sell[k]