15% off all plans & roadmaps Use code

See plans

Best Time to Buy and Sell Stock II

Updated

TL;DR: You can make as many buy and sell trades as you like, but you can hold at most one share at a time. A two-state dynamic programming pass, one state for holding and one for not holding, finds the best profit in a single scan.

Problem

You get an integer array prices. The value prices[i] is the price of one share on day i.

Each day you can buy one share, sell your share, or do nothing. You can never hold more than one share. You may also buy and sell on the same day.

Return the largest profit you can make.

Example 1

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 at price 1 and sell on day 3 at price 5, for a gain of 4. Then buy on day 4 at price 3 and sell on day 5 at price 6, for a gain of 3. The total is 7.

Example 2

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 at price 1 and sell on day 5 at price 5, for a gain of 4. The total is 4.

Example 3

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: Every move loses money, so the best choice is to never buy. The profit is 0.

Constraints

  • 1 <= prices.length <= 3 * 10^4
  • 0 <= prices[i] <= 10^4

Constraints that matter

  • n up to 3 * 10^4 rules out any approach that tries every combination of trades, since that grows as 2^n.
  • Prices are at most 10^4, so the largest possible total is about 3 * 10^8. A 32-bit int holds it, but Java, C++ and C# code should still use int only after checking this bound.
  • Because trades are unlimited, you never need to count how many trades you made. Only the holding state and the cash matter.
  • Prices can be 0, so a zero-cost buy is valid and ties between equal prices must not break the logic.

View on LeetCode

Hints

Hint 1

Each day you are in one of two states: you hold a share or you do not.

Hint 2

Try every sequence of decisions.

Solution

Intuition

Each day you are in one of two states: you hold a share or you do not. The best profit you can have depends on which state you end the day in, so you track the best value for each state.

It is like a ledger with two running totals, one for cash in hand and one for the best value while holding a share. Each day you rewrite both totals from yesterday's pair, and that pair is the only memory you keep.

The trades are unlimited, so the count of past trades does not matter. Yesterday's decision affects today in only two ways: whether you still own a share, and how much cash you have. That means yesterday's two numbers are enough to compute today's two numbers.

The transitions are short. Without a share today, you either had no share yesterday or you sold your share at today's price. With a share today, you either kept yesterday's share or you spent yesterday's cash buying at today's price. Every path through the days falls into one of these two choices, so the scan finds the best value.

Watch the pattern animation

Worked example

Input: prices = [2, 4, 1, 7, 5, 3, 6]
Output: 11
Explanation: Buy at 2 and sell at 4 for +2. Buy at 1 and sell at 7 for +6. Buy at 3 and sell at 6 for +3. The gains add up to 11, and no other set of trades does better on this array.

Approach 1: Brute force recursion

Try every sequence of decisions. On each day you can buy, sell or wait, and the valid moves depend only on whether you hold a share. A recursive function takes the current day and a holding flag. It tries waiting, and it tries the one trade the flag allows.

It returns the best total from that point on, and the answer is the best total from day 0 with no share. The recursion is correct because it covers every legal sequence of trades. It is slow because each day makes two recursive calls, and those calls branch again on the next day. The number of calls doubles with each extra day, so a few dozen days already take a long time.

Steps

  1. Write a function best(day, holding) that returns the most profit you can make from day onward.
  2. If day equals the length of prices, return 0, since no days are left to trade.
  3. Compute skip as best(day + 1, holding), which means doing nothing today.
  4. If holding is true, compute act as prices[day] + best(day + 1, false), which sells today. Otherwise compute act as -prices[day] + best(day + 1, true), which buys today.
  5. Return the larger of skip and act.
  6. Call best(0, false) and return the result.

Dry run

Start on day 0 with no share. One of the many paths the recursion explores is this one: buy at 2 on day 0, sell at 4 on day 1, buy at 1 on day 2, sell at 7 on day 3, buy at 3 on day 5, and sell at 6 on day 6.

The running total goes -2, then +4 gives 2, then -1 gives 1, then +7 gives 8, then -3 gives 5, then +6 gives 11.

The recursion compares this path with every other path and keeps the largest total, which is 11, matching the expected output.

Complexity

TimeO(2^n)
SpaceO(n)

Let n be the length of prices. Each call makes two more calls, and the recursion stops after n levels, so the call tree has about 2^n nodes. The stack holds at most n frames at once, so the extra space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)

        def best(day, holding):
            # no days left, so no more profit
            if day == n:
                return 0
            skip = best(day + 1, holding)
            if holding:
                act = prices[day] + best(day + 1, False)  # sell today
            else:
                act = -prices[day] + best(day + 1, True)  # buy today
            return max(skip, act)

        return best(0, False)

The Stock problems infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Stock problems

Part of Dynamic Programming (DP) Patterns

Approach 2: Two-state DP, one scanOptimalStock problems

What's slow: the recursion recomputes the same (day, holding) pair along many paths. There are only 2n such pairs, so most of the calls repeat work.

The insight that fixes it: the answer for day i depends only on the two values from day i-1. Compute the values forward, day by day, and keep only two numbers. cash is the best profit with no share, and hold is the best value with one share. Start with cash = 0 and hold = -prices[0], since buying on day 0 costs that price.

Each day, the new cash is the larger of yesterday's cash and yesterday's hold plus today's price. The new hold is the larger of yesterday's hold and yesterday's cash minus today's price. Both use yesterday's values, so compute both before you assign either.

Why it is correct. After each day, the two numbers are the best profit with no share and the best value with one share. Any sequence of trades up to today ends in one of those two states, so every path is covered. Each update takes the best of all paths reaching a state, so no better answer is ever thrown away.

Steps

  1. Set cash = 0 and hold = -prices[0].
  2. For each price p from day 1 onward, compute newCash = max(cash, hold + p).
  3. Compute newHold = max(hold, cash - p) using the cash from before this day.
  4. Assign cash = newCash and hold = newHold.
  5. After the last day, return cash.

Dry run

The table shows the two states after each day for prices = [2, 4, 1, 7, 5, 3, 6].

DayPricecash afterhold afterWhy
020-2Start. Buying on day 0 costs 2.
142-2Sell at 4 gives -2 + 4 = 2. Buying at 4 gives 0 - 4 = -4, which loses to -2.
2121Buy at 1 from cash 2 gives 2 - 1 = 1.
3781Sell at 7 gives 1 + 7 = 8.
4583Buy at 5 from cash 8 gives 3.
5385Buy at 3 from cash 8 gives 5.
66115Sell at 6 gives 5 + 6 = 11.

The final cash is 11, which matches the expected output.

Complexity

TimeO(n)
SpaceO(1)

Let n be the length of prices. The loop runs n - 1 times, and each pass does a fixed number of comparisons and additions, so the time is O(n). The method keeps only cash, hold and a loop index, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        cash = 0             # best profit with no share
        hold = -prices[0]    # best value while holding one share
        for p in prices[1:]:
            # both right-hand sides use yesterday's values
            cash, hold = max(cash, hold + p), max(hold, cash - p)
        return cash

Common mistakes

  • hold = 0 as the starting value, in the line that sets hold before the loop. Holding a share on day 0 costs its price, so start with hold = -prices[0].
  • hold = max(hold, -prices[i]), copied from the one-trade version. That line ignores the cash you earned earlier. Use cash - prices[i] so each buy is funded by past profit.
  • Returning hold instead of cash. The answer must end with no share held, so return the cash state.
  • Computing the new hold with the already updated cash, as in hold = max(hold, cash - p) after cash was reassigned. Compute both new values from yesterday's values first, or use a temporary variable.
  • Writing the brute force recursion without a day limit or without the holding flag. Then it cannot tell a buy from a sell, and it may return a wrong total or never stop.
  • Reading prices[i + 1] inside the loop for the last day. The loop should stop at the last index, and the code should never read past the array.

Edge cases

  • A single price, such as [5]. Only one day exists, so no trade is possible and the answer is 0.
  • A strictly falling array, such as [7,6,4,3,1]. Every buy loses money, so the answer is 0.
  • A strictly rising array, such as [1,2,3,4,5]. One long trade or four short trades both give 4, so the answer is 4.
  • Flat prices, such as [3,3,3]. Nothing rises, so the answer is 0.
  • A zero price followed by a higher one, such as [0,0,5]. Buying at 0 is legal, and the answer is 5.
  • The largest input, with 3 * 10^4 prices alternating between 0 and 10^4. The loop does about 3 * 10^4 steps and the result is about 3 * 10^8, which still fits in a 32-bit int.

Follow-ups interviewers ask

What if you may make at most two transactions?
Track four states instead of two: the first buy, the first sell, the second buy and the second sell. Each state keeps its best value and updates from the previous day, so the time stays O(n) and the space stays O(1).
Can you avoid the state machine and use only the price changes?
Yes. Add every positive difference between consecutive days, prices[i] - prices[i-1] when it is above 0. A rise from day a to day c equals the sum of the daily rises in between, so the total is the same. This runs in O(n) time and O(1) space.
What if each trade costs a fee?
Subtract the fee when you sell. The sell update becomes cash = max(cash, hold + p - fee), and the buy update stays hold = max(hold, cash - p). The same two-state scan still works in O(n) time and O(1) space.

Best Time to Buy and Sell Stock II FAQ

What is the time complexity of Best Time to Buy and Sell Stock II?

The two-state DP runs in O(n) time because it makes one pass over the n prices with constant work per day. The brute force recursion takes O(2^n) time because each day branches into two calls.

Why use dynamic programming for Best Time to Buy and Sell Stock II?

The best result on each day depends only on the state from the day before. Because the trades are unlimited, that state is only holding or not holding, so two numbers capture everything the future needs.

Can Best Time to Buy and Sell Stock II be solved in O(1) extra space?

Yes. The two-state DP stores cash and hold and nothing else. The greedy version of the same problem also uses O(1) space.

Why does the brute force recursion fail on large inputs?

Each day makes two recursive calls, so the number of calls doubles per day. With n up to 3 * 10^4, the calls would take far longer than any time limit, and deep recursion can also exhaust the stack in Python.

Asked at

See which companies ask this — Pro

Practise it