需求
prices: [7, 1, 5, 3, 6, 4]
prices[i]: 股票在第 i 天的价格
求最大利润(只能交易一次)
分析
低买高卖,在之前低价买入,记录当天的最低价以及利润点,明天也是这样。
Show Code
const maxProfit = (prices) => {
let min = prices[0];
let profit = 0;
for(let price of prices) {
min = Math.min(min, price);
profit = Math.max(profit, price - min);
}
return profit
}
// test
const prices = [7, 1, 5, 3, 6, 4];
console.log(maxProfit(prices)) // 5