The problem. You are given an array prices where prices[i] is a stock's price on day i. Choose one day to buy a share and a later day to sell it. Return the largest profit you can make — or 0 if no trade makes money.
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5 buy on day 1 (price 1), sell on day 4 (price 6)
Input: prices = [7, 6, 4, 3, 1]
Output: 0 the price only falls, so don't tradeOrder matters: in the first example the highest price is 7, but it comes before the lowest price, so you can't buy at 1 and sell at 7. And if every trade loses money, you simply don't trade — the answer is never negative.
For every buy day, try every later sell day and keep the biggest difference.
function maxProfit(prices) { let best = 0; for (let buy = 0; buy < prices.length; buy++) { for (let sell = buy + 1; sell < prices.length; sell++) { best = Math.max(best, prices[sell] - prices[buy]); } } return best;}Time O(n²), space O(1). About 5 billion comparisons for 100,000 days. For each buy day, the inner loop is really just looking for the highest price after it — and it recomputes that from scratch every time.
Compute that "highest price from day i to the end" for every day once, walking backwards. Then each buy day needs a single subtraction.
function maxProfit(prices) { const n = prices.length; const maxAfter = new Array(n); // highest price from day i to the end maxAfter[n - 1] = prices[n - 1]; for (let i = n - 2; i >= 0; i--) maxAfter[i] = Math.max(prices[i], maxAfter[i + 1]); let best = 0; for (let i = 0; i < n; i++) best = Math.max(best, maxAfter[i] - prices[i]); return best;}Time O(n), space O(n). Two passes instead of n² pairs. The only cost left is the extra array.
Flip the question around. Instead of asking "when should I buy?", pretend today is the day you sell. Then the best day to have bought is simply the cheapest day before today — one number, not an array.
So walk forward once, carrying minPrice (the cheapest price so far) and maxProfit (the best sale so far). Selling today earns price - minPrice; if that beats maxProfit, keep it.
The bars show the price on each day. Watch min move to every new low, and maxProfit grow only when selling today beats the best so far.
Time O(n), space O(1). One pass, two variables.
O(n²)Every buy day is paired with every later sell day: about n²/2 pairs.
O(1)Just the best profit and two indexes.
O(n)[7, 6, 4, 3, 1] returns 0.[5] returns 0; you can't buy and sell on the same day.[3, 8, 2, 9]: buying at 2 and selling at 9 beats buying at 3.[4, 4, 4] returns 0.This is Kadane's algorithm in disguise: a trade's profit is the sum of the day-to-day price changes between buying and selling, so the best trade is the maximum subarray of those changes.
Two passes: one builds the max-to-the-right array, one reads it.
O(n)An extra array with one entry per day.
O(n)One pass, and each day does O(1) work.
O(1)Only two variables: the cheapest price and the best profit.