Skip to content
Decoder

Best Time to Buy and Sell Stock

Easy

Problem

prices[i] is a stock's price on day i. You may buy once and then sell once on a later day. Return the largest profit you can make, or 0 if no trade makes money.

Example 1

Input
prices = [7, 1, 5, 3, 6, 4]
Output
5
Why
buy at 1, sell at 6

Example 2

Input
prices = [7, 6, 4, 3, 1]
Output
0
Why
prices only fall

Example 3

Input
prices = [2, 4, 1]
Output
2
Why
buy at 2, sell at 4

Constraints

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

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.