Best Time to Buy and Sell Stock II solution explained
Best Time to Buy and Sell Stock II asks for the most profit from a list of daily prices when you may buy and sell as many times as you like but hold at most one share at a time. The answer is the sum of every day-to-day price increase: any profitable trade is a run of daily changes, and collecting only the positive ones is both achievable and the best possible. That is one pass, O(n) time and O(1) memory.
By Evin JohnPublished 8 min read
The problem, restated
You see the closing price of one stock for each of the next n days, all in advance. On any day you may buy one share if you hold none, or sell the share you hold. There is no limit on the number of round trips and no fee. What is the most money you can make? Holding two shares at once is not allowed, and selling before buying is not allowed.
| Prices | Best profit | One way to get it |
|---|---|---|
| [3, 8, 2, 6, 9] | 12 | Buy 3 sell 8 (+5), buy 2 sell 9 (+7) |
| [4, 6, 5, 9, 1, 7] | 12 | +2, then +4, then +6 |
| [1, 2, 3, 4] | 3 | Buy at 1 and sell at 4, or trade every day: same total |
| [9, 7, 4, 1] | 0 | Prices only fall, so never trade |
| [5] | 0 | One day leaves no room for a trade |
What the interviewer is looking for
The code is short, so the interview is really about the argument. Can you explain why adding up rises is optimal and not just a lucky heuristic? Can you show the trades it corresponds to? And when the interviewer adds a fee or a cooldown, do you have a method that adapts, or does the greedy idea fall apart? This page covers the greedy answer, its proof, and the state-based version that carries over to the harder variants.
Follow-ups
- A fee per completed trade. Greedy on daily changes breaks, because small rises are no longer worth a fee. The two-state DP handles it by subtracting the fee on each sale.
- A cooldown day after each sale. Add a third state for the day after selling; see the cooldown variant linked below.
- At most k trades. Track one pair of hold and free values per allowed trade, k pairs in all, updated each day in order.
- Report the trades. Buy at each local low and sell at the next local high.
Brute force
On each day you either act (buy if empty-handed, sell if holding) or wait. Trying every sequence of choices is O(2^n). It is useful as a reference to test against, and saying it out loud shows the decision structure that the DP version captures with just two numbers.
def max_profit_slow(prices, day=0, holding=False):
if day == len(prices):
return 0
wait = max_profit_slow(prices, day + 1, holding)
if holding:
act = prices[day] + max_profit_slow(prices, day + 1, False)
else:
act = -prices[day] + max_profit_slow(prices, day + 1, True)
return max(wait, act)The greedy answer: sum the rises
Walk the prices once. Whenever today's price is above yesterday's, add the difference. That is the entire algorithm. Picture buying yesterday and selling today for each rising day. Consecutive rising days then merge into one longer trade, since holding through a rising stretch earns the same total as the sum of its daily rises.
def max_profit(prices):
profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
profit += prices[i] - prices[i - 1]
return profitfunction maxProfit(prices) {
let profit = 0;
for (let i = 1; i < prices.length; i++) {
const change = prices[i] - prices[i - 1];
if (change > 0) profit += change;
}
return profit;
}Why the greedy sum is optimal
Any single trade that buys on day i and sells on day j earns prices[j] - prices[i], and that difference equals the sum of the daily changes from day i to day j. A set of non-overlapping trades therefore earns a sum of daily changes over disjoint stretches of days. The largest such sum you could hope for takes every positive daily change and no negative one, which is exactly what the greedy loop adds. It is also achievable, by buying at the bottom of every rising stretch and selling at its top. So the greedy total is both an upper bound and reachable.
Showing the actual trades
def trades(prices):
result, i, n = [], 0, len(prices)
while i < n - 1:
while i < n - 1 and prices[i + 1] <= prices[i]:
i += 1 # slide down to a local low
buy = i
while i < n - 1 and prices[i + 1] > prices[i]:
i += 1 # climb to a local high
if i > buy:
result.append((buy, i))
return resultFor [3, 8, 2, 6, 9] this returns the day pairs (0, 1) and (2, 4): buy at 3, sell at 8, buy at 2, sell at 9. Fewer trades than one per rising day, same profit.
The state version, for when the rules change
Keep two numbers as you move through the days: free, the best profit so far if you end the day holding nothing, and hold, the best profit so far if you end the day holding a share (counting the purchase price as spent). Each day, free becomes the better of staying free or selling today, and hold becomes the better of keeping the share or buying today. Without a fee this gives the same answer as the greedy loop. With a fee, subtract it on every sale and the greedy loop is no longer correct, but this one still is.
def max_profit_states(prices, fee=0):
free, hold = 0, float("-inf")
for p in prices:
free, hold = max(free, hold + p - fee), max(hold, free - p)
return freeThe tuple assignment reads the previous day's free and hold on the right side, so a sale and a new purchase never happen on the same day. Doing both at the same price would gain nothing, so nothing is lost, and the result matches the exhaustive search with or without a fee.
Complexity
| Approach | Time | Extra memory | Handles a fee? |
|---|---|---|---|
| Try every choice | O(2^n) | O(n) stack | Yes |
| Sum of positive daily changes | O(n) | O(1) | No |
| Local low and high pairs | O(n) | O(number of trades) | No |
| Two states per day | O(n) | O(1) | Yes |
Edge cases
- Zero or one day: profit 0.
- Flat prices: 0, and the trade list is empty.
- Strictly falling prices: 0.
- Rises separated by equal prices, such as [1, 3, 3, 5], where the greedy sum is 4 and one trade from 1 to 5 also earns 4.
Common mistakes
- Solving the one-trade version (track the lowest price so far) when unlimited trades are allowed.
- Assuming a fee can be handled by subtracting it from each daily rise.
- In the state version, updating hold with the new free value from the same day without meaning to, then being unable to explain why it still works.
- Counting the profit of a local low to high run and also its individual daily rises, which counts it twice.
How to explain it out loud
Fictional example
- Candidate
- Any trade from day i to day j earns the sum of the daily changes between them. So whatever trades I make, I am collecting some daily changes and skipping others.
- Candidate
- The best I could ever collect is every positive change and none of the negative ones, and I can actually do that by buying at each low and selling at the next high. So I just add up the rises. One pass, constant memory.
- Candidate
- If you add a fee per trade, that argument breaks, so I would switch to two running values, the best profit while holding and while not holding, and subtract the fee when I sell.
Related problems
Best Time to Buy and Sell Stock with Cooldown adds a forced rest day after each sale, which the greedy sum cannot handle but a third state can. Distinct Subsequences is a good next dynamic programming problem if you want to move from day-by-day states to a two-string table.
Practicing with Natively
The proof is the part most people skip, and it is what interviewers remember. Practicing on Mac or Windows, you can have Natively read the problem from a screenshot and suggest an approach to set beside your own after you try it, and its transcript of your mock shows whether you explained why summing rises is optimal. Details on the AI interview assistant.
Questions people ask
How do you solve Best Time to Buy and Sell Stock II?
Walk through the prices once and add every positive difference between a day and the day before. That total is the maximum profit with unlimited trades and at most one share held.
Why does summing daily price increases give the maximum profit?
A trade from day i to day j earns the sum of the daily changes between them, so any set of trades collects some daily changes. Taking every positive change and no negative one is the most possible, and it is achievable by trading each rising stretch.
What is the time complexity of Best Time to Buy and Sell Stock II?
O(n) time and O(1) extra memory for n days, for both the greedy sum and the two-state DP.
How do you handle a transaction fee?
Keep two values per day: the best profit holding nothing and the best profit holding a share. Selling moves from hold to free and adds the price minus the fee; the greedy sum of rises no longer works.
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.
