AlgoFrames

Best time to buy and sell once

Warm-up · Write code · about 8 min

prices[i] is the price of a stock on day i. Buy one share on one day and sell it on a later day.

Return the largest profit. If no trade makes money, return 0.

Example 1

Input:

[[7,1,5,3,6,4]]

Output:

5

Buy at 1, sell at 6.

Example 2

Input:

[[7,6,4,3,1]]

Output:

0

Prices only fall, so do not trade.

Constraints

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴

Learn the idea first: State machine DP: stock problems, a visual lesson.

More State machine DP: stock problems problems