Skip to content
Onsite

Best Time to Buy and Sell Stock

EasyP1Coding

prices[i] is the price of a stock on day i. You may buy on one day and sell on a later day, once. Return the maximum profit you can make. If no profitable trade exists, return 0.

Example 1

Input
prices = [7,1,5,3,6,4]
Output
5
Why
Buy at 1 on day 1, sell at 6 on day 4.

Example 2

Input
prices = [7,6,4,3,1]
Output
0
Why
Prices only fall, so do not trade.

Example 3

Input
prices = [1,2]
Output
1

Constraints

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

Hints

Run checks the 3 visible tests, Submit all 8.