Best Time to Buy and Sell Stock
Buy once, sell once later, maximise profit. Scan left to right keeping the cheapest price so far; selling today earns price - minSoFar. The best of those is the answer.
Traced input: prices = [7, 1, 5, 3, 6, 4] → 5. Original problem: neetcode.io/problems/buy-and-sell-crypto
Complexity
BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)
One pass, two variables.
Key idea
- The best sell day for today is fixed; the only question is the cheapest earlier buy day.
- Keep
minPriceas you go, so that question is O(1). - If prices only fall, the best profit stays 0 (don't trade).
Common mistakes
- Selling before buying: the min must come from earlier days only.
- Initialising profit to a negative number; the answer is never below 0.
- Tracking the global max and min separately ignores their order.
Solution
Java
int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE, best = 0;
for (int i = 0; i < prices.length; i++) {
minPrice = Math.min(minPrice, prices[i]);
best = Math.max(best, prices[i] - minPrice);
}
return best;
}Python
def maxProfit(prices: List[int]) -> int:
min_price, best = float("inf"), 0
for p in prices:
min_price = min(min_price, p)
best = max(best, p - min_price)
return bestC++
int maxProfit(vector<int>& prices) {
int minPrice = INT_MAX, best = 0;
for (int p : prices) {
minPrice = min(minPrice, p);
best = max(best, p - minPrice);
}
return best;
}Edge cases
Each one has its own trace in the interactive view.
| Case | Input | Answer |
|---|---|---|
| Prices only fall No profitable trade, so don't trade. | prices = [7, 6, 4, 3, 1] | 0 |
| Single day You can't buy and sell on different days. | prices = [5] | 0 |
| Max before min 9 − 1 isn't allowed (wrong order); 3 − 1 = 2 is. | prices = [9, 1, 3] | 2 |
| Flat prices Every trade earns 0. | prices = [3, 3, 3] | 0 |
| Best at the end The minimum moves to 1, then 7 − 1 = 6 beats 4 − 2. | prices = [2, 4, 1, 7] | 6 |