InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Best Time to Buy and Sell Stock III

hard Original ↗
Solving tips
  • Recognize this as a state-machine DP: the 'at most two transactions' cap plus a holding/not-holding flag is your state, so carry both.
  • Unroll into four rolling scalars (buy1, sell1, buy2, sell2) updated once per day; charge the transaction on the buy and never double-count it.
  • Initialize buys to negative infinity, not 0, or a strictly falling price series fabricates a phantom free share.
  • Target O(n) time and O(1) space; a brute-force pass over all interval pairs is O(n squared) and times out at 10^5.

Problem

You are given prices, where prices[i] is the price of a stock on day i. You may complete at most two transactions to maximize your profit. A transaction is one buy followed by a later sell. You may not hold more than one share at a time — you must sell before you buy again — and you never have to trade at all. Return the maximum total profit you can achieve.

Examples

  • prices = [3, 3, 5, 0, 0, 3, 1, 4]6 — buy at 0 (day 3) sell at 3 (day 5) for +3, then buy at 1 (day 6) sell at 4 (day 7) for +3; total 6.
  • prices = [1, 2, 3, 4, 5]4 — one transaction (buy 1, sell 5) already captures the whole rise; a second transaction adds nothing.
  • prices = [7, 6, 4, 3, 1]0 — prices only fall, so the best move is to make no transaction at all.

Constraints

  • 1 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^5
  • At most two non-overlapping transactions.
  • The 10^5 length forces an O(n) or O(n·k) solution with k = 2; anything that tries all pairs of intervals (O(n²) or worse) times out.

Think about it first

Hint 1 "At most two" strongly suggests carrying the number of transactions you have left as part of your state. On each day you also either currently hold a share or you don't — that's another piece of state.
Hint 2 Think of a small state machine per day: for each `(transactions remaining, holding or not)` you know the best profit reachable. Each day you can rest (keep the state) or act (buy if not holding, sell if holding). Buying commits one of your two transactions.
Hint 3 Because k is fixed at 2, you can even unroll the state into four running numbers, updated once per day in order: best profit after the 1st buy, after the 1st sell, after the 2nd buy, after the 2nd sell. Each is a simple `max` of "keep" vs "act now". Return the value after the 2nd sell.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.