Best Time to Buy and Sell Stock
EasySliding Window
You are given an array prices, where prices[i] is the price of a stock on day i.
You may make at most one trade: buy one share on some day, then sell it on a strictly later day. Return the largest profit (sell price minus buy price) you can make.
If no trade makes money (for example, the price only falls), return 0, which means you simply do not trade.
Example 1
- Input:
- prices = [4, 9, 1, 5]
- Output:
- 5
- Explanation
- Buying at 4 on day 0 and selling at 9 on day 1 earns 5. The lowest price, 1 on day 2, is a worse buy because the best later price is only 5, a profit of 4.
Example 2
- Input:
- prices = [9, 1, 5, 3, 8]
- Output:
- 7
- Explanation
- Buy at 1 on day 1 and sell at 8 on day 4 for a profit of 7. The 9 on day 0 cannot be a sell price because nothing was bought before it.
Example 3
- Input:
- prices = [8, 6, 4, 3]
- Output:
- 0
- Explanation
- The price falls every day, so every possible trade loses money. Not trading gives 0.
Constraints
- 1 ≤
prices.length≤ 105 - 0 ≤
prices[i]≤ 104