← Practice · Sliding window

Best Time to Buy and Sell Stock Easy

prices[i] is a stock price on day i. Choose one day to buy and a later day to sell to maximize profit. Return the maximum profit, or 0 if no profit is possible.

Examples

  • [7,1,5,3,6,4] -> 5 (buy at 1, sell at 6)
  • [7,6,4,3,1] -> 0

Define a function named maxProfit in JavaScript.

00:00

JavaScript · Tab indents · Ctrl/⌘+Enter runs the tests