15% off all plans & roadmaps Use code

See plans

Best Time to Buy and Sell Stock III

Updated

TL;DR: You may make at most two buy-and-sell trades, and you must sell before buying again. Track four running values, the best balance after each buy and each sell, and the last sell value is the answer after one pass.

Problem

You are given an array prices where prices[i] is the price of a given stock on day i.

Find the maximum profit you can make. You may complete at most two transactions.

You may not hold more than one stock at a time. You must sell a stock before you buy again.

Example 1

Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3 - 0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4 - 1 = 3.

Example 2

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5 - 1 = 4. You cannot buy on day 1, buy again on day 2, and sell later, because that holds two transactions at once. You must sell before buying again.

Example 3

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: No transaction is done, so the max profit is 0.

Example 4

Input: prices = [1]
Output: 0

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^5

Constraints that matter

  • prices.length up to 10^5 rules out checking every pair of days, which is about 5 * 10^9 pairs.
  • Two trades is a fixed, small number, so the state fits in a few variables instead of a table over trades.
  • prices[i] up to 10^5 keeps every profit small. The answer is at most 2 * 10^5, so a 32-bit int is safe.
  • Prices can be 0. A buy state set to 0 would mean buying for free, so the starting buy state must come from a real price.

View on LeetCode

Hints

Hint 1

This is a dynamic programming problem over states.

Hint 2

Two trades that do not overlap always have a day where the first trade is finished and the second one has not started.

Solution

Intuition

This is a dynamic programming problem over states. On any day you are in one of four situations: holding the first stock, having finished one trade, holding the second stock, or having finished two trades. The question is the best value you can have in each situation after each day.

Picture four labeled cups in a row, one per trading stage, and each day you only pour from the cup before yours. Each cup keeps the best balance reached at its stage so far, and the last cup holds the answer.

The limit of two trades is the clue. A fixed number of trades means the number of states is fixed, so each state can live in one variable instead of a table indexed by day. Each state depends only on the previous day's states and today's price.

Each variable stores the best value for its state so far. A later state reads the best earlier state, and keeping only the maximum at each step is safe because a lower value never helps later. The final sell state holds the answer.

Watch the pattern animation

Worked example

Input: prices = [5, 4, 3, 2, 1, 2, 3, 4, 5]
Output: 4
Explanation: The price falls from 5 to 1, then rises back to 5. Buy at the bottom price 1 on day 4 and sell at 5 on day 8 for a profit of 4. Two trades also give 4: buy at 1 and sell at 2 on day 5, then buy at 2 on day 5 and sell at 5 on day 8, for 1 + 3 = 4.

Approach 1: Brute force: try every split point

Two trades that do not overlap always have a day where the first trade is finished and the second one has not started. Splitting the array at that point gives two independent halves. Each half needs only its best single trade. The naive version tries every split and rescans both halves from scratch each time, which repeats the same work over and over.

Steps

  1. Set best to 0.
  2. For each split k from 0 to n, treat days before k as the left side and days from k on as the right side.
  3. Scan the left side. Keep the lowest price seen and the largest gap between a later price and that lowest price.
  4. Scan the right side the same way to get its best single trade.
  5. Add the two results and update best if the sum is larger.
  6. Return best.

Dry run

Use the example [5, 4, 3, 2, 1, 2, 3, 4, 5] and try k = 4. The left side is [5, 4, 3, 2], where prices only fall, so its best single trade is 0. The right side is [1, 2, 3, 4, 5], where buying at 1 and selling at 5 gives 4. The total is 4, so best becomes 4, and no other split gives more.

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the length of prices. The outer loop runs n + 1 times, and each run scans every day once on the left and once on the right, which is n steps. So the total work is about n times n, which is O(n^2). The solution stores only a few integers, 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:
        n = len(prices)

        def one_trade(lo, hi):
            # best single buy-then-sell using only days lo to hi-1
            low = float('inf')
            best = 0
            for i in range(lo, hi):
                low = min(low, prices[i])
                best = max(best, prices[i] - low)
            return best

        best = 0
        for k in range(n + 1):
            # days before k form the first side, days from k on form the second
            best = max(best, one_trade(0, k) + one_trade(k, n))
        return best

Approach 2: Prefix and suffix best profit

What's slow in the brute force is the repeated scan, since each split rescans both halves from the start. The insight that fixes it is that each half can be built once and reused for every split.

One forward pass records the best single trade that finishes on or before each day. One backward pass records the best single trade that starts on or after each day. A final pass adds the two values at every split.

Steps

  1. Build left, where left[i] is the best single trade using days 0 to i. Track the lowest price so far.
  2. Build right, where right[i] is the best single trade using days i to n - 1. Scan backward and track the highest price so far.
  3. For each index i, add left[i] and right[i].
  4. Keep the largest sum and return it.

Dry run

For the example, left is [0, 0, 0, 0, 0, 1, 2, 3, 4]. The lowest price falls to 1 on day 4, then left grows as prices rise. right is [4, 4, 4, 4, 4, 3, 2, 1, 0]. On day 4 (price 1), right[4] is 4, from buying at 1 and selling at 5 on day 8. The sums at every index are 4, so the largest is 4.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of prices. The left pass, the right pass and the final loop each do one step per day. So the total is about 3n steps, which is O(n). The two arrays hold n values each, so the 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)
        # left[i]: best single trade using days 0..i
        left = [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)
        # right[i]: best single trade using days i..n-1
        right = [0] * n
        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))

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 3: One-pass state machineOptimalStock problems

What's slow in the two-pass version is storing an array of answers for every day. You only need the previous day's four values to compute today's. The four values are the best balance after the first buy, the best profit after the first sell, the best balance after the second buy, and the best profit after the second sell. Each one comes from the previous value and today's price, so one pass with four variables is enough.

Steps

  1. Set buy1 and buy2 to -prices[0]. Set sell1 and sell2 to 0.
  2. For each price p, set buy1 to the larger of buy1 and -p. This is the best balance after buying the first stock.
  3. Set sell1 to the larger of sell1 and buy1 + p. This is the best profit after one finished trade.
  4. Set buy2 to the larger of buy2 and sell1 - p. The second buy starts with the profit from the first trade.
  5. Set sell2 to the larger of sell2 and buy2 + p.
  6. Return sell2.

Dry run

Start with buy1 = -5, sell1 = 0, buy2 = -5, sell2 = 0, since the buy states begin at -prices[0]. Each row applies the six updates above to one price.

DayPricebuy1sell1buy2sell2
05-50-50
14-40-40
23-30-30
32-20-20
41-10-10
52-11-11
63-12-12
74-13-13
85-14-14

On day 5, sell1 becomes 1 (buy at 1, sell at 2). Then buy2 becomes -1 because 1 - 2 = -1, which is the same as the first buy. On day 8, sell2 becomes 4, and the function returns 4.

Complexity

TimeO(n)
SpaceO(1)

Let n be the length of prices. Each day does a fixed set of comparisons and additions, and there are n days, so the total work is O(n). The solution keeps four integers no matter how long the input is, so the extra space is O(1).

Each variable holds the best value for its state after that day, so the final sell2 is the best two-trade profit.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        buy1 = -prices[0]   # best balance after the first buy
        sell1 = 0           # best profit after the first sell
        buy2 = -prices[0]   # best balance after the second buy
        sell2 = 0           # best profit after the second sell
        for p in prices:
            buy1 = max(buy1, -p)
            sell1 = max(sell1, buy1 + p)
            buy2 = max(buy2, sell1 - p)
            sell2 = max(sell2, buy2 + p)
        return sell2

Common mistakes

  • buy2 = max(buy2, buy1 - p) uses the first buy instead of the first sell. The second buy then ignores the profit from the first trade. Use sell1 - p.
  • buy1 = 0 or buy2 = 0 at the start. This means buying for free, which inflates the profit. Start the buy states at -prices[0] or at negative infinity.
  • buy2 = max(buy2, sell1 + p) has a sign error. Buying adds cost, so the price must be subtracted.
  • Returning sell1 instead of sell2. That answer ignores the second trade and fails inputs where two trades beat one.
  • Setting sell1 or sell2 to negative infinity. When prices only fall, the answer must be 0 because doing nothing is allowed. Start the sell states at 0.

Edge cases

  • prices = [1] returns 0, because there is no pair of days to trade.
  • prices = [7, 6, 4, 3, 1] returns 0, because prices only fall and no trade is profitable.
  • prices = [1, 2, 3, 4, 5] returns 4. The second trade adds nothing, and the answer must not count the same rise twice.
  • prices = [1, 2, 1, 2] returns 2. Two separate trades beat one trade that holds through the dip.
  • prices = [4, 4, 4] returns 0, because equal prices create no gain.
  • Length 10^5 with large prices: the answer is at most 2 * 10^5, so a 32-bit int holds it.

Follow-ups interviewers ask

What if you may make any number of transactions?
Buy before every rise and sell at its peak, which is the same as adding every positive day-over-day increase. This runs in O(n) time and O(1) space. The limit of two trades is what forces the four-state machine.
What if you may make at most k transactions?
Keep k buy states and k sell states, and update them in the same order each day. The work is O(n * k) time and O(k) space. When k is at least n / 2, the limit never binds, so the unlimited greedy solution applies.
What if prices arrive one at a time, and you need the answer after each day?
The state machine already works this way. Each day reads only the current price and the four stored values. The answer after any day is the current sell2, and memory does not grow with the stream.

Best Time to Buy and Sell Stock III FAQ

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

The optimal solution runs in O(n) time, where n is the number of days, because it does a constant amount of work per day in one pass. The brute force split approach runs in O(n^2) time.

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

The problem has a fixed set of states, and each state depends only on the previous day. Dynamic programming stores the best value for each state, so you never need to revisit an earlier choice. The limit of two trades keeps the number of states constant.

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

Yes. The state machine keeps four integers no matter how long the input is. The prefix and suffix approach needs O(n) arrays, so it does not meet that bound.

Can you sell and buy on the same day?

Yes, the rules allow it, and it adds zero profit because the sale and the purchase cancel out. The state machine handles this case correctly without a special check.

Does the greedy solution from the unlimited version work here?

No. The greedy approach takes every rise, which can use more than two trades. Keeping the best value for each state respects the two-trade limit.

Asked at

See which companies ask this — Pro

Practise it