【leetcode】121. 买卖股票的最佳时机

154 阅读1分钟

leetcode-121.png

贪心算法
思路:记录下每次遍历的最小值,然后计算当前价格与最小值的差价即可,保存最大差价。
这里题没有多少技巧

var maxProfit = function (prices) {
    let minPrice = prices[0]
    let profit = 0
    for (let i = 0; i < prices.length; ++i) {
        // 记录最小值
        minPrice = Math.min(minPrice, prices[i])
        // 记录最大利润
        profit = Math.max(profit, prices[i] - minPrice)
    }
    return profit === 0 ? 0 : profit
};