prices[i] is a stock's price on day i. Choose one day to buy and a later day to sell to maximize profit. Return the max profit, or 0 if no profit is possible.
The best sell today pairs with the cheapest price seen so far. Track that minimum as you scan.
1function maxProfit(prices: number[]): number {2let minPrice = Infinity, best = 0;3for (const price of prices) {4if (price < minPrice) minPrice = price;5else best = Math.max(best, price - minPrice);6}7return best;8}
minPrice = ∞, best = 0.
Space: play/pause · ←/→: step