public int maxProfit(int[] prices) { int minPrice = prices[0]; // cheapest buy so far int best = 0; for (int price : prices) { if (price < minPrice) { minPrice = price; // new cheapest day } int profit = price - minPrice; // sell today best = Math.max(best, profit); } return best;}
- day
- —
- price
- —
- minPrice
- —
- profit
- —
- best
- 0
Why it works
- Brute force tries every (buy, sell) pair with the buy first: O(n²).
- Fix the sell day, and the best buy day is just the cheapest day before it. So carry one number, the running minimum, instead of rescanning the past.
- Invariant: after day
i,minPriceis the lowest price in days 0..i andbestis the best trade that sells by dayi. One pass, two variables: O(n) time, O(1) space. - Pitfall: the answer is not max − min of the whole array, because the max may come first. In
[3,8,2,5,1,4]that gives 8 − 1 = 7, but you cannot sell on day 1 what you buy on day 4. A new minimum never resetsbest. - Sliding-window view: NeetCode writes the same loop with
l(buy) andr(sell), jumpingl = rwheneverprices[r] < prices[l]. There,prices[l]isminPrice. - Follow-up, Stock II (122): unlimited trades. Then just add up every day-to-day rise.