Best Time to Buy and Sell Stock III solution explained
Best Time to Buy and Sell Stock III gives you daily prices and allows at most two complete trades, one share at a time. Keep four running values: the best balance after the first buy, after the first sell, after the second buy and after the second sell, each updated from the one before it as you scan the prices once. The answer is the value after the second sell, found in O(n) time and O(1) memory; a prefix and suffix version that splits the days in two is a good stepping stone.
By Evin JohnPublished 8 min read
The problem, restated
You are given a list of daily prices for one stock. You may buy one share and later sell it, and you may do that at most twice in total. You cannot hold two shares at once, so the second purchase must come after the first sale. Return the largest total profit, or 0 if no trade helps.
| Prices | One trade | At most two | Unlimited | Best two trades |
|---|---|---|---|---|
| [4, 1, 5, 3, 8, 2, 6] | 7 | 11 | 13 | 1 to 8, then 2 to 6 |
| [2, 6, 3, 9, 1, 4] | 7 | 10 | 13 | 2 to 6, then 3 to 9 |
| [3, 8, 1, 9, 2, 7] | 8 | 13 | 18 | 3 to 8, then 1 to 9 |
| [1, 2, 3, 4, 5] | 4 | 4 | 4 | A single trade from 1 to 5 |
| [7, 6, 4, 1] | 0 | 0 | 0 | No trade |
The first row shows why you cannot just take the two biggest rises. The rises are 1 to 5, 3 to 8 and 2 to 6, worth 4, 5 and 4. The best pair of those is 9, but merging the first two into one trade, 1 to 8, frees the second trade for 2 to 6, and that totals 11.
What the interviewer is testing
Most candidates know the one-trade and unlimited-trade versions. This one checks whether you can generalize instead of patching. Interviewers like to see the split idea first, because it shows you can reduce a new problem to one you know, and then the four-variable version, because it shows you can see the problem as a chain of states. A strong candidate also explains why updating the four values in place, in order, is safe.
Follow-ups
- At most k trades. Use k buy values and k sell values; see the last code block below.
- k larger than half the number of days. The limit can no longer bind, so fall back to summing every rise.
- A fee per trade. Subtract it when selling (or buying); the chain is otherwise unchanged.
- Report the trades. Use the prefix and suffix version, keep the day indexes of each best trade and the best split.
Brute force: try every split
Two trades never overlap, so there is a day where the first one is over and the second has not begun. For each possible split day, compute the best single trade on the left part and on the right part with the usual running-minimum scan, and keep the best sum. Letting both parts share the split day is harmless: selling and buying again on the same day is the same as holding.
def one_trade(prices):
best, low = 0, float("inf")
for p in prices:
low = min(low, p)
best = max(best, p - low)
return best
def max_profit_two_split(prices):
best = 0
for i in range(len(prices)):
best = max(best, one_trade(prices[: i + 1]) + one_trade(prices[i:]))
return bestPrefix and suffix in linear time
The split version repeats work. left[i] = best single trade within days 0 to i can be filled left to right with a running minimum. right[i] = best single trade within days i to the end can be filled right to left with a running maximum. The answer is the largest left[i] + right[i].
def max_profit_two_arrays(prices):
n = len(prices)
if n == 0:
return 0
left, right = [0] * n, [0] * n
low = prices[0]
for i in range(1, n):
low = min(low, prices[i])
left[i] = max(left[i - 1], prices[i] - low)
high = prices[-1]
for i in range(n - 2, -1, -1):
high = max(high, prices[i])
right[i] = max(right[i + 1], high - prices[i])
return max(left[i] + right[i] for i in range(n))Four running states
Think of your cash balance as you go. buy1 is the best balance after making the first purchase (so it is negative), sell1 the best after the first sale, buy2 the best after the second purchase and sell2 the best after the second sale. Each value either stays as it was or takes one step from the value before it in the chain.
| State | Meaning | Update on price p |
|---|---|---|
| buy1 | Holding the first share | max(buy1, -p) |
| sell1 | First trade done | max(sell1, buy1 + p) |
| buy2 | Holding the second share | max(buy2, sell1 - p) |
| sell2 | Second trade done | max(sell2, buy2 + p) |
def max_profit_two(prices):
buy1 = buy2 = float("-inf")
sell1 = sell2 = 0
for p in prices:
buy1 = max(buy1, -p)
sell1 = max(sell1, buy1 + p)
buy2 = max(buy2, sell1 - p)
sell2 = max(sell2, buy2 + p)
return sell2function maxProfitTwoTrades(prices) {
let buy1 = -Infinity;
let buy2 = -Infinity;
let sell1 = 0;
let sell2 = 0;
for (const p of prices) {
buy1 = Math.max(buy1, -p);
sell1 = Math.max(sell1, buy1 + p);
buy2 = Math.max(buy2, sell1 - p);
sell2 = Math.max(sell2, buy2 + p);
}
return sell2;
}Updating in place looks like it might let one day count twice, for example buying and selling on the same day. It does, but a same-day buy and sell earns exactly 0, so it never creates profit that is not really there. That is why no saved copies are needed here, unlike the cooldown version.
Trace [2, 6, 3, 9, 1, 4]. After 2: buy1 -2, sell1 0, buy2 -2, sell2 0. After 6: sell1 4, sell2 4. After 3: buy2 max(-2, 4 - 3) = 1. After 9: sell1 7, sell2 max(4, 1 + 9) = 10. After 1: buy1 -1, buy2 max(1, 7 - 1) = 6. After 4: sell2 max(10, 6 + 4) = 10. The answer is 10, and the late buy2 of 6 shows the algorithm also considered 2 to 9 followed by 1 to 4, which also totals 10.
At most k trades
function maxProfitKTrades(k, prices) {
if (k === 0 || prices.length < 2) return 0;
if (k >= Math.floor(prices.length / 2)) {
let total = 0;
for (let i = 1; i < prices.length; i++) {
total += Math.max(0, prices[i] - prices[i - 1]);
}
return total;
}
const buy = new Array(k).fill(-Infinity);
const sell = new Array(k).fill(0);
for (const p of prices) {
for (let t = 0; t < k; t++) {
buy[t] = Math.max(buy[t], (t === 0 ? 0 : sell[t - 1]) - p);
sell[t] = Math.max(sell[t], buy[t] + p);
}
}
return sell[k - 1];
}Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Every split, single-trade scan on each side | O(n^2) | O(n) for the slices |
| Prefix and suffix arrays | O(n) | O(n) |
| Four states | O(n) | O(1) |
| 2k states for k trades | O(n · k) | O(k) |
Edge cases
- Empty list or a single day: 0.
- Prices that only fall: 0, never a negative number.
- Prices that only rise: one trade is optimal and the second adds nothing.
- Equal prices throughout: 0.
- Two good rises separated by a shallow dip, where one merged trade plus a later trade beats the two biggest rises.
Common mistakes
- Collecting every rise and keeping the two largest, which example one defeats.
- Starting buy1 or buy2 at 0, which pretends a share was free.
- In the k-trade loop, buying from sell[t] instead of sell[t - 1], which lets one trade feed itself.
- Applying the unlimited greedy when k is small, or forgetting it when k is large and the 2k loop gets slow.
- Returning max(sell1, sell2) as if it were needed; sell2 is never smaller than sell1 because a second same-day trade adds 0.
How to explain it out loud
Fictional example
- Candidate
- Two trades never overlap, so there is a split day. If I precompute the best single trade ending by each day and starting from each day, the answer is the best left plus right. That is linear with two arrays.
- Candidate
- I can shrink that to four variables: the best balance after the first buy, the first sell, the second buy and the second sell. Each one either keeps its value or takes one step from the previous state at today's price.
- Candidate
- In-place updates are fine because a same-day buy and sell earns zero. It is O(n) time and O(1) memory, and the same chain with 2k values handles any k.
Related problems
Best Time to Buy and Sell Stock II removes the trade limit, which makes a greedy sum work. Best Time to Buy and Sell Stock with Cooldown adds a rest day instead of a limit. Minimum Cost For Tickets is another day-by-day DP, and Maximal Rectangle also turns a two-sided question into a single pass with running values.
Practicing with Natively
This problem rewards practicing the explanation as much as the code. In a practice round on Mac or Windows, Natively can read the problem from a screenshot and suggest an approach to compare with yours after you have tried it, and the transcript afterward shows whether your reason for in-place updates came across. See the AI interview assistant.
Questions people ask
How do you solve Best Time to Buy and Sell Stock III?
Keep four values: buy1 = max(buy1, -p), sell1 = max(sell1, buy1 + p), buy2 = max(buy2, sell1 - p) and sell2 = max(sell2, buy2 + p), updated for each price p. The answer is sell2.
Why can't I take the two largest price rises?
Two separate rises can be worth more merged into one trade, which frees the second trade for a later rise. Example: in [4, 1, 5, 3, 8, 2, 6] the best is 1 to 8 plus 2 to 6, not the two biggest rises.
What is the time complexity of Stock III?
O(n) time and O(1) extra memory for n days. The prefix and suffix version is also O(n) but uses two arrays.
How do you extend Stock III to at most k transactions?
Keep k buy values and k sell values and chain them the same way, O(n times k). If k is at least half the number of days, just sum every rise.
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.
