Skip to problem
←

Best Time to Buy and Sell Stock IV

Hard 0 attempts

You're given an array of stock prices and an integer k. Find the maximum profit obtainable using at most k buy-sell transactions, where a new transaction can't start until the previous one has been closed out (you must sell before buying again).

Function contract

Implement maxProfit(k, prices), where k is the maximum number of completed buy-then-sell transactions.

Output: The maximum profit using at most k transactions, holding at most one share at a time. Return 0 if no trade is profitable.

Example 1

Input
k = 2
prices = [2,4,1]
Output
2

Example 2

Input
k = 2
prices = [3,2,6,5,0,3]
Output
7
Constraints
  • 1 <= k <= 100
  • 1 <= prices.length <= 1000
  • 0 <= prices[i] <= 1000

DP with State Machine

dp[t][0] stores the best cash balance after exactly t completed sales with no stock held. dp[t][1] stores the best balance while holding the stock for transaction t (after t - 1 completed sales).

For each price, either keep each state or sell/buy. Update transaction counts in descending order so a purchase uses the preceding day’s lower-transaction state. The answer is the best cash balance over 0 through k completed sales. When k is large enough, collect every positive consecutive price difference.

javascript
function maxProfit(k, prices) {
  const n = prices.length;
  if (k >= n / 2) {
    let profit = 0;
    for (let i = 1; i < n; i++) profit += Math.max(0, prices[i] - prices[i - 1]);
    return profit;
  }
  const dp = Array.from({ length: k + 1 }, () => [-Infinity, -Infinity]);
  dp[0][0] = 0;
  for (const p of prices) {
    for (let t = k; t >= 1; t--) {
      dp[t][0] = Math.max(dp[t][0], dp[t][1] + p);
      dp[t][1] = Math.max(dp[t][1], dp[t - 1][0] - p);
    }
  }
  return Math.max(...dp.map((d) => d[0]));
}

Time: O(nk) | Space: O(k)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript