Best Time to Buy and Sell Stock
Part of Practice: Longest Valid Windows
You are given an array prices where prices[i] is the price of a stock on day i. You may buy the stock on one day and sell it on a later day, and you get exactly one buy and one sell. Return the largest profit you can make. If no profitable trade exists (prices only fall), return 0.
Constraints that matter: the array has at least 1 price, up to about 10^5 entries, so an O(n^2) check of every buy/sell pair is too slow.
Examples
- Input:
- prices = [7,1,5,3,6,4]
- Output:
- 5
Buy on day 1 (price 1) and sell on day 4 (price 6). Profit is 6 - 1 = 5. Buying at 7 and selling at 1 is not allowed because you must sell after you buy.
- Input:
- prices = [7,6,4,3,1]
- Output:
- 0
Prices only go down, so every trade loses money. The best move is not to trade, which gives profit 0.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.