Algorithms · Visualized

DP: Stock — At Most 2 Transactions

Dynamic Programming

Break problems into overlapping subproblems and store answers.

Maximises profit from at most two buy/sell transactions over a price series, holding at most one share at a time. Time: O(n) average, O(n) worst; space: O(1) — four running values.

Big-O: The most-asked interview category — 35 classics here.

Stock — At Most 2 Transactions

Dynamic Programming

Maximises profit from at most two buy/sell transactions over a price series, holding at most one share at a time. Four running states are carried forward day by day: 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 state is the better of keeping yesterday’s value or making today’s trade, which is exactly the DP recurrence for this problem.

How Stock — At Most 2 Transactions Works

  1. Initialise buy1 = −prices[0], sell1 = 0, buy2 = −∞ and sell2 = 0.
  2. For each later price p, update buy1 = max(buy1, −p).
  3. Update sell1 = max(sell1, buy1 + p).
  4. Update buy2 = max(buy2, sell1 − p).
  5. Update sell2 = max(sell2, buy2 + p) and return sell2.

Stock — At Most 2 Transactions Worked Example

Input:

Prices [3,3,5,0,0,3,1,4]: buy1=−3, sell1 reaches 2 at price 5, buy2 drops to −2 at price 0, and sell2 reaches 6 at price 4 — two trades of 3→5 and 0→4.

DP: Stock — At Most 2 TransactionsO(n)
Four rolling states (buy1/sell1/buy2/sell2) scanned day by day.
3
0
3
1
5
2
0
3
0
4
3
5
1
6
4
7
buy1-3
sell10
buy2-3
sell20
Step 1 / 10
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
At most 2 transactions: track buy1/sell1 (first round trip) and buy2/sell2 (second) day by day.
Python · Dynamic Programming Algorithms in Code
def max_profit_2(prices):
    buy1 = buy2 = float('-inf')
    sell1 = sell2 = 0
    for p in prices:              # four rolling states
        buy1 = max(buy1, -p)
        sell1 = max(sell1, buy1 + p)
        buy2 = max(buy2, sell1 - p)
        sell2 = max(sell2, buy2 + p)
    return sell2  # ≤ 2 transactions, O(n)

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Stock — At Most 2 Transactions Time & Space Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1) — four running values

When to Use Stock — At Most 2 Transactions

  • Trading and budgeting puzzles where a limited number of transactions is allowed.
  • A compact introduction to state-machine DP: each state is one line and the transitions are explicit.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.