Best Time to Buy and Sell Stock IV (LeetCode 188): Solution and Explanation

Hard
Array
Dynamic Programming

You get daily stock prices and an integer k, and may complete at most k buy and sell transactions without holding more than one share at a time. Return the maximum total profit.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A direct DP defines dp[t][i] as the best profit using up to t transactions by day i, and for each state tries every possible buy day. That inner loop makes it O(k × n²), which is too slow for large inputs. The fix is to notice that the best buy day for the current transaction can be carried along as a running value instead of being searched every time.

Generalize the two-transaction trick. Let buy[i] be the lowest effective cost of holding a share during transaction i, where effective cost means the price paid minus the profit already locked in by the first i - 1 transactions. Let sell[i] be the best profit after completing i transactions. Then for each price, buy[i] = min(buy[i], price - sell[i - 1]) and sell[i] = max(sell[i], price - buy[i]). Each transaction builds on the one before it, like a chain.

There is also an important shortcut. A profitable transaction needs at least two days, so with n days there can be at most n // 2 useful transactions. If k is at least that, the limit never binds and the problem becomes Stock II, where you sum every positive daily change. Handling that case separately avoids allocating huge arrays when k is enormous.

Approach: Transaction-indexed DP with an unlimited shortcut

  1. Return 0 for an empty price list.
  2. If k >= n // 2, return the sum of every positive difference prices[i] - prices[i - 1].
  3. Otherwise create buy filled with infinity and sell filled with 0, both of size k + 1, where index 0 is the base case of no transactions.
  4. For each price, loop i from 1 to k.
  5. Update buy[i] = min(buy[i], price - sell[i - 1]), then sell[i] = max(sell[i], price - buy[i]).
  6. Return sell[k].

Step-by-step example

k = 2, prices = [3, 2, 6, 5, 0, 3]
  1. Here n = 6 and n // 2 = 3, so k = 2 is a real limit and the DP runs.
  2. Price 3 sets buy[1] = 3 and buy[2] = 3. Price 2 lowers both to 2. Profits are still 0.
  3. Price 6: sell[1] = 4, buy[2] = min(2, 6 - 4) = 2, sell[2] = 4.
  4. Price 5: buy[2] = min(2, 5 - 4) = 1; profits stay 4.
  5. Price 0: buy[1] = 0, and buy[2] = min(1, 0 - 4) = -4, which is buying again at 0 with the profit of 4 in hand.
  6. Price 3: sell[2] = max(4, 3 - (-4)) = 7. The answer is 7, from buying at 2 and selling at 6, then buying at 0 and selling at 3.

Code: Python, Java, C++

1class Solution:
2    def maxProfit(self, k: int, prices: List[int]) -> int:
3        if not prices:
4            return 0
5        n = len(prices)
6        # If k >= n/2, unlimited transactions
7        if k >= n // 2:
8            return sum(max(0, prices[i] - prices[i-1]) for i in range(1, n))
9
10        # buy[i] = min cost to buy for i-th transaction
11        # sell[i] = max profit after i-th transaction
12        buy = [float('inf')] * (k + 1)
13        sell = [0] * (k + 1)
14
15        for price in prices:
16            for i in range(1, k + 1):
17                buy[i] = min(buy[i], price - sell[i-1])
18                sell[i] = max(sell[i], price - buy[i])
19
20        return sell[k]

Time and space complexity

Time

O(n × k)

Each of the n prices runs an inner loop over k transactions, unless the shortcut applies, in which case it is O(n).

Space

O(k)

Only the two arrays of length k + 1 are stored; the shortcut uses O(1).

Other approaches

Full 2D table (time O(n × k), space O(n × k))

Store dp[t][i] for every transaction count and day, using a running maximum of dp[t - 1][j] - prices[j] to avoid the inner loop. Same time, but O(n × k) memory, which is useful if you need to reconstruct the trades.

Valley-peak merging with heaps (time O(n log n), space O(n))

Collect all valley-peak pairs, then repeatedly merge or drop the least valuable ones until k remain, using a stack and a heap. It achieves O(n log n) independent of k, but is far harder to get right.

Common mistakes

  • Skipping the k >= n // 2 shortcut causes memory or time blowups when k is very large, such as k = 1,000,000,000.
  • Writing the shortcut as k >= n is still correct but misses many cases where the cheaper path applies.
  • Initializing buy with 0 instead of infinity means no purchase ever looks cheaper than free, so sell stays at its starting value and the answer is wrong.
  • Indexing sell[i - 1] with i starting at 0 reads sell[-1], which in Python silently wraps to the last element.

Frequently asked questions

Why is k >= n / 2 the same as unlimited transactions?

Each transaction needs a buy day and a later sell day, so n days support at most n / 2 non-overlapping profitable trades. Beyond that, the limit can never bind.

What do the buy and sell arrays mean?

sell[i] is the best profit after completing i transactions, and buy[i] is the lowest effective cost of holding the share for transaction i, already discounted by sell[i - 1].

What is the time complexity of Stock IV?

O(n × k) for the DP path and O(n) when the unlimited shortcut applies. Space is O(k).

How does this relate to Stock III?

Stock III is this problem with k fixed at 2. Its four variables are exactly buy[1], sell[1], buy[2] and sell[2] from this solution.