Skip to content

Best Time to Buy and Sell Stock

EasySliding Window
Decode it first. Clues, constraints, pattern and plan before any code.

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.

prices = [7, 1, 5, 3, 6, 4]   →  5   (buy at 1, sell at 6)
prices = [7, 6, 4, 3, 1]      →  0   (prices only fall)
prices = [2, 4, 1]            →  2   (buy at 2, sell at 4)

Constraints

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