121 · sliding window · easy
Best time to buy and sell stock
One price per day. Buy on one day, sell on a later day, once. What's the most you can make? If there's no way to profit, make 0 by not trading.
The one rule
Brute force tries every buy day against every later sell day — O(n²). Almost all of those pairs are pointless. For any sell day, the only buy worth considering is the cheapest price that came before it. Buying anything pricier on an earlier day can only lower the profit.
profit if sold today = prices[today] - cheapest price so far
answer = the best of those, or 0 So a single left-to-right pass only has to carry two numbers: the cheapest price so far, and the best profit so far. Order is built in — the cheapest price "so far" is always on an earlier day than the one being sold on, so buy-before-sell never has to be checked.
The left / right scan · O(n) time, O(1) space
left pins the cheapest day seen so far, right is today. right moves every step. If today's price is higher than left's, it's a candidate sale, so compare and keep the max. If it's at or below, left jumps to right: that lower price is a better buy for every day still to come, and any profit the old left could have made is already banked in maxGains.
Step through it. The second input shows left jumping mid-scan without losing the earlier profit; the third shows what a falling market returns.
var maxProfit = function (prices) {
let left = 0, right = 1;
let maxGains = 0;
while (right < prices.length) {
if (prices[left] < prices[right]) {
let profit = prices[right] - prices[left];
maxGains = Math.max(maxGains, profit);
} else {
left = right;
}
right += 1;
}
return maxGains;
};
Two things worth saying out loud. right starts at 1, so a single-day input never enters the loop and returns 0. And left only ever jumps forward, so it's one pass: O(n) time, two indices and two numbers of space.
Brute force, for contrast
var maxProfit = function (prices) {
let maxGains = 0;
for (let i = 0; i < prices.length; i++) {
for (let j = i + 1; j < prices.length; j++) {
maxGains = Math.max(maxGains, prices[j] - prices[i]);
}
}
return maxGains;
};
Every pair with j > i, so the ordering is enforced by the loop bounds. Correct, and O(n²) — on LeetCode's upper bound of 10⁵ days that's five billion comparisons.
Complexity
| approach | time | space |
|---|---|---|
| brute force · every buy/sell pair | O(n²) | O(1) |
| left / right scan | O(n) | O(1) |
Edge cases
[7, 6, 4, 3, 1]→ 0. Prices only fall;leftjumps every step and no profit is ever computed. 0 means "don't trade", never a negative.[5]→ 0.right = 1is already out of range.[3, 3, 3]→ 0. Equal prices count as a drop (<, not<=), soleftkeeps moving and nothing is banked.[2, 4, 1, 7]→ 6, not 5. The best buy comes after an earlier profitable pair; jumpingleftdoesn't lose the banked 2, and 7 − 1 beats it.[1, 2]→ 1. The smallest profitable input.
Same instinct elsewhere
"Carry the best prior value instead of re-checking every pair" is the whole trick, and it recurs: Maximum Subarray (Kadane's) carries the best sum ending here the same way this carries the cheapest price so far. Best Time to Buy and Sell Stock II drops the "once" rule and becomes "sum every uphill step."