CodingNodes / 2-D Dynamic Programming / Best Time to Buy and Sell Stock III System design Space play · ←→ step · R restart

Problem

You are given the price of one stock on each day in the list prices.

You may complete at most two buy-then-sell trades. You can hold only one share at a time, so you must sell before you buy again.

Return the largest total profit you can make. Return 0 if no trade makes money.

Constraints

  • 1 ≤ prices.length ≤ 100000
  • 0 ≤ prices[i] ≤ 100000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: One pass over the prices, with four constant-time updates per day.

Space: Only four numbers are kept, no matter how long the price list is.

Track the best balance at four moments: after the first buy, after the first sell, after the second buy and after the second sell. Each day, update them in that order. A buy is the better of keeping the old value or paying today's price out of the previous stage's balance. A sell is the better of keeping the old value or adding today's price to the buy balance. The answer is the second sell.