Skip to content
Decoder

Best Time to Buy and Sell Stock III

Hard

Problem

prices[i] is a stock's price on day i. You may complete at most two trades, where a trade is one buy followed later by one sell, and you can hold at most one share at a time (sell before you buy again). Return the largest total profit you can make, or 0 if no trade helps.

Example 1

Input
prices = [6, 2, 5, 3, 9, 4, 8]
Output
11
Why
buy 2, sell 9; buy 4, sell 8

Example 2

Input
prices = [3, 4, 6, 7, 11]
Output
8
Why
one trade is enough

Example 3

Input
prices = [9, 7, 5, 3]
Output
0

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^5

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.