121. Best Time to Buy and Sell Stock
¶
- Time: $O(n)$
- Space: $O(1)$
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 | |
var maxProfit = function(prices) {
let low = Infinity, best = 0;
for (const p of prices) {
low = Math.min(low, p);
best = Math.max(best, p - low);
}
return best;
};