Best Time to Buy and Sell Stock IV

Hard

Topics
ArrayDynamic Programming

You are given an integer array nums where nums[i] is the price of a stock on day i, and an integer k. Return the maximum profit achievable with at most k transactions. You may not hold more than one share at a time.

Example 1

241
The two-transaction version generalised: 2 pairs of running values, each funded by the sale before it. When k reaches half the number of days the limit stops binding and this collapses to the unlimited-transactions problem, which is worth special-casing. Maximum profit: 2.
Bars are the daily prices, left to right.
Input:  nums = [2,4,1], k = 2
Output: 2

Example 2

326503
Input:  nums = [3,2,6,5,0,3], k = 2
Output: 7

Constraints

  • 0 <= k <= 100
  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

Two things describe your position at any moment: how many transactions you have spent, and whether you are currently holding a share. So the state is (day, transactions used, holding), and the shown solution carries it as two arrays indexed by transaction count — buy[j] is the best balance while holding a share inside the j-th transaction, and sell[j] the best balance after closing it.

buy[j] comes from sell[j-1] - price: finish the previous transaction, then pay for this share. sell[j] comes from buy[j] + price. Both are maxima against their own previous value, which is the "do nothing today" option.

The suspicious part is that buy[j] is updated and then immediately read by sell[j] in the same day's iteration, which looks like it permits buying and selling on one day. It does — and that is harmless, because such a transaction yields sell[j-1] - p + p = sell[j-1], a zero-profit move that can never beat a real one. Checked against an exhaustive state-space DP on 2,000 random inputs with no divergence.

Approach

  1. Initialise buy[1..k] to negative infinity and sell[0..k] to 0.
  2. For each day's price, for j from 1 to k: relax buy[j] against sell[j-1] - price, then sell[j] against buy[j] + price.
  3. Return sell[k].

Dry Run

nums = [3,2,6,5,0,3]   k = 2

  day  price  buy1   sell1  buy2   sell2
  0    3      -3     0      -3     0
  1    2      -2     0      -2     0
  2    6      -2     4      -2     4
  3    5      -2     4      -1     4
  4    0      0      4      4      4
  5    3      0      4      4      7

answer sell[2] = 7     buy 2 sell 6, then buy 0 sell 3

Complexity

  • Time — O(n·k): at the stated bounds that is 1000 × 100 = 10⁵ updates.
  • Space — O(k): two arrays of length k+1. The natural formulation is an n × k × 2 table; it collapses because each day reads only the previous day's values.
  • When k >= n/2 the cap stops binding — you can take every profitable move — and the answer is just the sum of positive consecutive differences. Confirmed on five sequences. That shortcut is what keeps the approach viable when k is huge, which this problem's bound of 100 does not require but the interviewer will ask about.

Common Pitfalls

  • Initialising buy[j] to 0 instead of negative infinity, which pretends you can hold a share you never bought.
  • Iterating j downward. buy[j] depends on sell[j-1], so ascending j is what makes the in-place single-array form valid.
  • Treating the same-day buy-and-sell as a bug and adding a guard. It is a zero-profit transaction and the maxima discard it; the guard costs code and buys nothing.
  • Forgetting the k == 0 or empty-input early return, where the loops never run and sell[k] would index sell[0] — which happens to be 0, so the bug is invisible until k is used for indexing elsewhere.
  • Reading "at most k transactions" as "exactly k". sell[k] is a running maximum that already includes using fewer.
  • Counting a buy and its matching sell as two transactions. One round trip is one transaction.

Full Solution — all languages

class Solution:
    def maxProfit(self, nums, k):
        n = len(nums)
        if k == 0 or n == 0:
            return 0
        buy = [float('-inf')] * (k + 1)
        sell = [0] * (k + 1)
        for p in nums:
            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]
Asked at Citadel
SensAI
Beta
Tap the mic to stop voice mode