InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

Best Time to Buy and Sell Stock III

hard Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug