Best Time to Buy and Sell Stock IV (LeetCode 188): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Return 0 for an empty price list.
- If
k >= n // 2, return the sum of every positive differenceprices[i] - prices[i - 1]. - Otherwise create
buyfilled with infinity andsellfilled with 0, both of size k + 1, where index 0 is the base case of no transactions. - For each price, loop
ifrom 1 to k. - Update
buy[i] = min(buy[i], price - sell[i - 1]), thensell[i] = max(sell[i], price - buy[i]). - Return
sell[k].
Step-by-step example
k = 2, prices = [3, 2, 6, 5, 0, 3]
- Here n = 6 and n // 2 = 3, so k = 2 is a real limit and the DP runs.
- Price 3 sets
buy[1] = 3andbuy[2] = 3. Price 2 lowers both to 2. Profits are still 0. - Price 6:
sell[1] = 4,buy[2] = min(2, 6 - 4) = 2,sell[2] = 4. - Price 5:
buy[2] = min(2, 5 - 4) = 1; profits stay 4. - Price 0:
buy[1] = 0, andbuy[2] = min(1, 0 - 4) = -4, which is buying again at 0 with the profit of 4 in hand. - 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]1class Solution {
2 public int maxProfit(int k, int[] prices) {
3 if (prices.length == 0) return 0;
4 int n = prices.length;
5 // If k >= n/2, unlimited transactions
6 if (k >= n / 2) {
7 int profit = 0;
8 for (int i = 1; i < n; i++) {
9 if (prices[i] > prices[i-1]) {
10 profit += prices[i] - prices[i-1];
11 }
12 }
13 return profit;
14 }
15
16 // buy[i] = min cost to buy for i-th transaction
17 // sell[i] = max profit after i-th transaction
18 int[] buy = new int[k + 1];
19 int[] sell = new int[k + 1];
20 Arrays.fill(buy, Integer.MAX_VALUE);
21
22 for (int price : prices) {
23 for (int i = 1; i <= k; i++) {
24 buy[i] = Math.min(buy[i], price - sell[i-1]);
25 sell[i] = Math.max(sell[i], price - buy[i]);
26 }
27 }
28 return sell[k];
29 }
30}1class Solution {
2public:
3 int maxProfit(int k, vector<int>& prices) {
4 if (prices.empty()) return 0;
5 int n = prices.size();
6 // If k >= n/2, unlimited transactions
7 if (k >= n / 2) {
8 int profit = 0;
9 for (int i = 1; i < n; i++) {
10 if (prices[i] > prices[i-1]) {
11 profit += prices[i] - prices[i-1];
12 }
13 }
14 return profit;
15 }
16
17 // buy[i] = min cost to buy for i-th transaction
18 // sell[i] = max profit after i-th transaction
19 vector<int> buy(k + 1, INT_MAX);
20 vector<int> sell(k + 1, 0);
21
22 for (int price : prices) {
23 for (int i = 1; i <= k; i++) {
24 buy[i] = min(buy[i], price - sell[i-1]);
25 sell[i] = max(sell[i], price - buy[i]);
26 }
27 }
28 return sell[k];
29 }
30};Time and space complexity
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).
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 // 2shortcut causes memory or time blowups when k is very large, such as k = 1,000,000,000. - Writing the shortcut as
k >= nis still correct but misses many cases where the cheaper path applies. - Initializing
buywith 0 instead of infinity means no purchase ever looks cheaper than free, sosellstays at its starting value and the answer is wrong. - Indexing
sell[i - 1]with i starting at 0 readssell[-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.