sagelearnai

Best Time to Buy and Sell Stock IV

Difficulty: Hard · Pattern: 1-D Dynamic Programming · LeetCode #188

You may complete at most k transactions, holding at most one share at a time. Return the maximum profit.

Examples

text
k = 2, prices = [2,4,1]        →  2
k = 2, prices = [3,2,6,5,0,3]  →  7    (buy 2 sell 6, buy 0 sell 3)

Hints

  1. Stock III used four variables for k = 2. Use arrays buy[1..k] and sell[1..k].
  2. If k ≥ n/2 the limit never binds, so it's just Stock II.

Approach

text
if 2k >= n: return sum of positive day-to-day differences
buy = [-inf]*(k+1); sell = [0]*(k+1)
for p in prices:
    for j in 1..k:
        buy[j]  = max(buy[j], sell[j-1] - p)
        sell[j] = max(sell[j], buy[j] + p)
return sell[k]

That's O(n·k) time and O(k) space. The shortcut matters when k is huge: without it, k = 10⁹ would be infeasible.

Complexity

Time: O(n·k). Space: O(k).

Python solution
def maxProfit(k, prices):
    n = len(prices)
    if 2 * k >= n:
        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]
JavaScript solution
function maxProfit(k, prices) {
  const n = prices.length;
  if (2 * k >= n) { let s = 0; for (let i = 1; i < n; i++) s += Math.max(0, prices[i] - prices[i - 1]); return s; }
  const buy = new Array(k + 1).fill(-Infinity), sell = new Array(k + 1).fill(0);
  for (const p of prices) for (let j = 1; j <= k; j++) {
    buy[j] = Math.max(buy[j], sell[j - 1] - p);
    sell[j] = Math.max(sell[j], buy[j] + p);
  }
  return sell[k];
}