Best Time to Buy and Sell Stock

EasySliding window

prices[i] is the price of a stock on day i. You may buy once and sell once, on a later day.

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

Examples

Example 1
Input:  prices = [8, 3, 6, 1, 5, 4]
Output: 4

Buy on day 3 at 1 and sell on day 4 at 5.

Example 2
Input:  prices = [9, 7, 4, 1]
Output: 0

The price only falls, so the best choice is not to trade.

Constraints

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

Stuck?

Hint 1

On any day, the best sale is that day’s price minus the lowest price before it.

Hint 2

Keep the lowest price so far and the best profit so far, in one pass.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur