我的js算法爬坑之旅- 买卖股票的最佳时机 III

116 阅读1分钟

第九十四天:力扣 123题,买卖股票的最佳时机 III

地址:leetcode-cn.com/problems/be…

思路:动态规划,和之前的买卖股票题目差不多

var maxProfit = function(prices) {
    const n = prices.length;
    let buy1 = -prices[0], buy2 = -prices[0];
    let sell1 = 0, sell2 = 0;
    for (let i = 1; i < n; i++) {
        buy1 = Math.max(buy1, -prices[i]);
        sell1 = Math.max(sell1, buy1 + prices[i]);
        buy2 = Math.max(buy2, sell1 - prices[i]);
        sell2 = Math.max(sell2, buy2 + prices[i]);
    }
    return sell2;
};

执行用时:120 ms, 在所有 JavaScript 提交中击败了69.35%的用户

内存消耗:48 MB, 在所有 JavaScript 提交中击败了95.09%的用户