121. Best Time to Buy and Sell Stock

枚举卖出价格,维护最低价格
js
var maxProfit = function (prices) {
let ans = 0
let minPrice = prices[0]
for (const p of prices) {
ans = Math.max(ans, p - minPrice)
minPrice = Math.min(minPrice, p)
}
return ans
}⚠️初始化成:minPrice = prices[0];
我们需要从第一天的价格开始,作为初始的 “最低买入价”,然后遍历后续每一天的价格,不断更新最低买入价,并计算当天卖出能获得的利润。