You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k. Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
f[k][i]
f[k][i] = max( f[k][i-1], max( prices[i] - prices[j] + f[k-1, j] for i in [0, i-1] ) ) = max( f[k][i-1], prices[i] + max( f[k-1, j] - prices[j] + for i in [0, i-1] ) )
f[k][0] = 0
f[0][i] = 0
def max_profit_with_k_transactions(K: int, prices: List[int]) -> int: n = len(prices) f = [[0] * (n) for _ in range(K + 1)] max_profit = 0 for k in range(1, K + 1): t = f[k - 1][0] - prices[0] for i in range(1, n): t = max(t, f[k - 1][i] - prices[i]) f[k][i] = max(f[k][i - 1], prices[i] + t) max_profit = max(max_profit, f[k][i]) return max_profit