Best Time to Buy and Sell Stock IV solution explained
Best Time to Buy and Sell Stock IV is solved with dynamic programming over two states per trade count: the best cash you can have while holding a share after starting your t-th trade, and the best cash after finishing it. One pass over the prices updates both arrays, which gives O(n·k) time and O(k) memory, and when k is at least half the number of days the cap no longer binds and a greedy sum of every rise is enough.
By Evin JohnPublished 9 min read
The problem in plain words
You get a list of prices, one per day, and a whole number k. A trade means buying one share on some day and selling it on a later day. You may make at most k trades, and you cannot buy again while you still own a share, so trades never overlap. Return the largest total profit you can reach. Doing nothing is always allowed, so the answer is never below zero.
| k | Prices | Best profit | How |
|---|---|---|---|
| 2 | [5, 2, 8, 1, 4, 9] | 14 | Buy at 2, sell at 8; buy at 1, sell at 9 |
| 1 | [5, 2, 8, 1, 4, 9] | 8 | With one trade, the single widest gap is 1 to 9 |
| 3 | [3, 6, 2, 7, 1, 5] | 12 | Three separate rises: 3, 5 and 4 |
| 2 | [9, 7, 4, 1] | 0 | Prices only fall, so you never trade |
| 0 | [1, 10] | 0 | No trades allowed at all |
The first two rows show why the cap matters. With k = 2 you take both rises separately. With k = 1 the best plan is not the first rise but the widest single gap, which skips a dip in the middle. Ask the interviewer a couple of things before coding: can k be larger than the number of days, can the list be empty, and are prices whole numbers?
Where it sits in the stock family
This is the general case of a well-known series. One trade is a running minimum. Unlimited trades is a sum of every upward step. Two trades is the classic hard variant. Interviewers like the k version because a candidate who truly understands the series can write one solution that covers all of them, while a candidate who memorized four separate tricks gets stuck. The real signal is state design: knowing that you only need to remember how many trades you have opened and whether you own a share.
Slow approach: pick a buy day for every sell day
A natural first DP asks: what is the best profit using up to t trades and only the first i + 1 days? Either day i is not a sell day, so the answer equals the one for day i - 1, or you sell on day i after buying on some earlier day j. In the second case you add the gain prices[i] - prices[j] to the best you could do with t - 1 trades up to day j. Trying every j makes each cell cost O(n), so the whole table costs O(k·n²) time and O(k·n) space.
def stock_k_slow(k, prices):
n = len(prices)
if n == 0:
return 0
best = [[0] * n for _ in range(k + 1)]
for t in range(1, k + 1):
for i in range(1, n):
top = best[t][i - 1]
for j in range(i):
top = max(top, prices[i] - prices[j] + best[t - 1][j])
best[t][i] = top
return best[k][n - 1]Look at the inner loop. For a fixed t, it maximizes best[t - 1][j] - prices[j] over every j before i. Its maximum over all j before i can only grow as i moves right, so you can carry it in a single variable instead of recomputing it. That observation is the whole jump to the fast version.
Main approach: two states per trade count
Keep two arrays of length k + 1. hold[t] is the most cash you can have after buying for your t-th trade and not yet selling. free[t] is the most cash you can have after completing t trades. Start with free filled with zeros and hold filled with minus infinity, because you cannot be holding before any purchase. Then walk through the prices once. On each day, for each t from 1 to k:
- Buy or keep holding: hold[t] becomes the larger of its old value and free[t - 1] - price. Buying opens trade t, so it starts from the cash left after t - 1 finished trades.
- Sell or keep waiting: free[t] becomes the larger of its old value and hold[t] + price.
The answer is free[k]. Updating in increasing t on the same day can let you sell and immediately rebuy, or buy and sell on one day, but both of those earn exactly zero, so they never inflate the result.
One shortcut matters for large k. A profitable trade needs at least two days, so you can never complete more than n / 2 useful trades. If 2k is at least n, the cap is irrelevant and the answer is simply the sum of every positive difference between consecutive days. Skipping this check lets a huge k build huge arrays for nothing.
def stock_k(k, prices):
n = len(prices)
if n < 2 or k == 0:
return 0
if 2 * k >= n:
return sum(max(0, prices[i] - prices[i - 1]) for i in range(1, n))
hold = [float("-inf")] * (k + 1)
free = [0] * (k + 1)
for p in prices:
for t in range(1, k + 1):
hold[t] = max(hold[t], free[t - 1] - p)
free[t] = max(free[t], hold[t] + p)
return free[k]function stockK(k, prices) {
const n = prices.length;
if (n < 2 || k === 0) return 0;
if (2 * k >= n) {
let total = 0;
for (let i = 1; i < n; i++) total += Math.max(0, prices[i] - prices[i - 1]);
return total;
}
const hold = new Array(k + 1).fill(-Infinity);
const free = new Array(k + 1).fill(0);
for (const p of prices) {
for (let t = 1; t <= k; t++) {
hold[t] = Math.max(hold[t], free[t - 1] - p);
free[t] = Math.max(free[t], hold[t] + p);
}
}
return free[k];
}Tracing the first example
Take k = 2 and prices [5, 2, 8, 1, 4, 9]. After day 0, hold[1] = -5 and hold[2] = -5. On day 1 the price is 2, so hold[1] improves to -2. On day 2 the price is 8: free[1] becomes -2 + 8 = 6, and hold[2] becomes 6 - 8 = -2 (sell and rebuy, a zero-value move). On day 3 the price is 1, so hold[2] improves to 6 - 1 = 5, meaning one finished trade worth 6 plus a share bought at 1. On day 4, free[2] reaches 9 by selling that second share at 4. On day 5 the price is 9, so free[2] = 5 + 9 = 14, the expected answer.
Complexity
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Try every buy day per sell day | O(k·n²) | O(k·n) | Fine to state, too slow for long price lists |
| Hold and free arrays | O(k·n) | O(k) | The expected answer |
| Greedy sum when 2k ≥ n | O(n) | O(1) | Use it before building the arrays |
With the shortcut in place, k is effectively capped at n / 2, so the worst case is O(n²) time only when k is close to that limit.
Edge cases to test
- k = 0, or a list with zero or one price: the answer is 0.
- Prices that never rise, such as a strictly falling list: the answer is 0, not a negative number.
- k far larger than the number of days, such as k = 1,000 with six prices: the shortcut should return the sum of rises without allocating big arrays.
Mistakes that cost points
- Starting hold at 0 instead of minus infinity, which pretends you got a share for free.
- Forgetting the large-k shortcut, so a k in the billions builds arrays that exhaust memory.
- Counting a trade on both the buy and the sell, which halves the real cap.
- Using a running minimum as in the one-trade version and trying to bolt on extra trades by hand. It breaks as soon as the best plan skips a small rise.
- Returning a negative value when no trade helps. Doing nothing is always an option.
How to explain it out loud
Fictional example
- Candidate
- Each day I only need to know two things: how many trades I have opened and whether I hold a share. So I keep hold[t] and free[t], the best cash in each situation.
- Candidate
- Holding for trade t comes from being free after t minus 1 trades and paying today's price. Being free after t trades comes from holding for trade t and selling today. One pass, k updates per day.
- Candidate
- If 2k is at least the number of days, the cap cannot bind, so I just add every rise. Total cost is O(n times k) time and O(k) space.
Other problems in this set
Picking the best set of non-overlapping choices is also the core of Maximum Profit in Job Scheduling, where intervals replace buy and sell days and a binary search replaces the running maximum. If you want a lighter warm-up that uses sorting and a greedy match instead of DP, try Assign Cookies. For a wider list of question types, see the algorithm interview questions.
Practice it with Natively
When you rehearse DP problems like this one, Natively can read the problem from a screenshot and suggest a state definition you can hold up against your own after a first attempt. It also keeps a transcript of a mock session on your computer, so you can check afterward whether you named the slow table, explained the two states clearly and remembered the large-k shortcut. More on an AI interview assistant for Mac and Windows.
Questions people ask
How do you solve Best Time to Buy and Sell Stock IV?
Keep two arrays indexed by trade count: the best cash while holding a share for trade t, and the best cash after finishing t trades. Update both for every price in one pass and return the finished value for k. It runs in O(n·k) time and O(k) space.
What happens when k is very large?
If 2k is at least the number of days, the cap can never bind, so the answer is the sum of every positive day-to-day price change. Check this first so you never build huge arrays.
Why start the holding state at minus infinity?
Because you cannot own a share before buying one. Starting at zero would act as if a share came for free and would overstate the profit.
How does Stock IV relate to the other stock problems?
It generalizes them. k = 1 is the one-trade version, k = 2 is the two-trade version, and a k of at least half the days behaves like unlimited trading, so one state machine covers the whole series.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
