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 ProgrammingMaximises 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
- Initialise buy1 = −prices[0], sell1 = 0, buy2 = −∞ and sell2 = 0.
- For each later price p, update buy1 = max(buy1, −p).
- Update sell1 = max(sell1, buy1 + p).
- Update buy2 = max(buy2, sell1 − p).
- 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.
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
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
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.