Problem 350577 · hard · Phase 03 Linear Management & Searching

At Most Two Trades

state machine · dynamic programming · stock trading

prices[i] is the price of a rare stamp on day i. You may complete at most two trades, each a buy on one day followed by a sell on a later or the same day, and you must sell the first stamp before buying the second. Return the largest total profit; return 0 if no profitable trade exists.

Examples

Input:  prices = [3, 8, 2, 9, 1, 4]
Output: 12
Explanation: Buy at 3, sell at 8 (+5); buy at 2, sell at 9 (+7).
Input:  prices = [9, 7, 5]
Output: 0

Constraints

  • 1 <= len(prices) <= 10**5, 0 <= prices[i] <= 10**6.
  • Target complexity: O(n) time, O(1) extra space.

Goals

  • Model four states: before/after the first buy and sell, and the second buy and sell
  • Update the states in an order that forbids overlapping trades
Starting Python…