TypeScript Max Profit
function maxProfit(a: number[]): number {
let price = a[0];
let profit = 0;
for (const v of a) {
price = Math.min(price, v);
profit = Math.max(profit, v - price);
}
return profit;
}
This tracks the lowest buy price seen so far and updates the best profit as it scans the prices once.