Best Time to Buy and Sell Stock III

HardDP · State Machine🧩 State Machine DPLeetCode #123 ↗Updated

Problem

prices[i] is a stock's price on day i. You may complete at most two buy→sell transactions, and you can hold at most one share at a time (sell before buying again). Return the maximum total profit, or 0 if no trade helps.
Input[3,3,5,0,0,3,1,4]Output6
Input[1,2,3,4,5]Output4
Input[7,6,4,3,1]Output0

1 ≤ n ≤ 105  ·  0 ≤ prices[i] ≤ 105  ·  at most 2 transactions, no overlap

Try it yourself

Java
class Solution {
    public int maxProfit(int[] prices) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Model each day with four running bests: buy1, sell1, buy2, sell2 (max cash after each action). Each one depends only on the previous state, so one pass with four variables solves it.
PatternState Machine DP

Instinct Each step you are in one of a few modes (holding, sold, cooling down) with rules for switching - keep one DP value per mode and update all of them every step.

Memory hack Name the moods, draw the moves, max the arrows - every arrow in your state diagram becomes exactly one line of code.

Open the State Machine DP guide →

Approaches

Brute ForceSplit Day + Naive One-Transaction Scan

Time O(n3)Space O(1)

Two non-overlapping trades are separated by some split day k: one lies in [0..k], the other in [k..n-1]. For each k, find the best single trade on each side by trying every buy/sell pair. (A single trade is the case where one side earns 0.)

Java
public int maxProfit(int[] prices) {
    int n = prices.length, best = 0;
    for (int k = 0; k < n; k++)
        best = Math.max(best, one(prices, 0, k) + one(prices, k, n - 1));
    return best;
}
private int one(int[] p, int lo, int hi) { // best single trade in p[lo..hi]
    int best = 0;
    for (int i = lo; i <= hi; i++)
        for (int j = i + 1; j <= hi; j++)
            best = Math.max(best, p[j] - p[i]);
    return best;
}

Obviously correct, but n × n2 work is hopeless at n = 105.

At a glance

LevelApproachTimeSpace
Brute ForceSplit Day + Naive One-Transaction ScanO(n3)O(1)
BetterPrefix & Suffix Best (Forward–Backward)O(n)O(n)
OptimalState Machine DP (4 Variables)O(n)O(1)
Common pitfalls
  • Summing the two largest single-trade gains — they may overlap in time.
  • Initialising buy states to 0 — implies a free share; use -∞ or -prices[0].
  • Forcing exactly two trades — one trade (or none) can be optimal.
Interview tips
  • Start from Stock I (one trade), then ask “where does the 2nd trade start?”.
  • Draw the 5-state chain: rest → buy1 → sell1 → buy2 → sell2.
  • Mention the k-transaction generalisation and the O(nk) cost.
Pattern
State machine DP → sequential decisions with a few modes (holding / not, count used) where each day depends only on yesterday.
My notes saved in this browser