Skip to content
CodeShare
All problems

Best Time to Buy and Sell Stock

Pick one day to buy and a later day to sell for the biggest profit.

EasyArraysGreedy

You're given an array prices where prices[i] is a stock's price on day i. Choose one day to buy and a later day to sell.

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

Examples

Example 1
Input
prices = [7, 1, 5, 3, 6, 4]
Output
5
Why
Buy at 1 (day 1) and sell at 6 (day 4).
Example 2
Input
prices = [7, 6, 4, 3, 1]
Output
0
Why
Prices only fall, so the best move is not to trade.

Constraints

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