All problems

Best Time to Buy and Sell Stock

Easy · sliding window

The list prices holds the price of one stock on each day: prices[i] is the price on day i.

You may buy the stock on one day and sell it on a later day. Return the largest profit you can make from that single buy and sell. If no pair of days gives a profit, return 0 (you simply do not trade).

You cannot sell before you buy, and you cannot hold more than one share.

Examples

Example 1

Input: prices = [7, 1, 5, 3, 6, 4]

Output: 5

Buy on day 1 at price 1, sell on day 4 at price 6: 6 - 1 = 5.

Example 2

Input: prices = [7, 6, 4, 3, 1]

Output: 0

The price only falls, so every trade loses money. Do nothing and return 0.

Example 3

Input: prices = [2, 4, 1]

Output: 2

Buy at 2, sell at 4. The price of 1 comes after the high, so it cannot be used to buy and sell earlier.

Constraints