Skip to content
  1. 买卖股票的最佳时机 III https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii

状态机,其实就是在跨天的最优解:

js
var maxProfit = function(prices) {
    
    // 这些变量都是利润
    let buy1 = -prices[0];
    let sell1 = 0;
    let buy2 = -prices[0];
    let sell2 = 0;

    for(let i=1;i<prices.length;i++){
        const p = prices[i];
        // 这里跨天的,所以不用快照。
        buy1 = Math.max(buy1, -p);
        sell1 = Math.max(sell1, buy1+sell1);
        buy2 = Math.max(buy2, sell1-p);
        sell2 = Math.max(sell2, buy2+p);
    }

    return sell2;
};
  1. 买卖股票的最佳时机 IV https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/description/

状态压缩,其实大差不差,你的利润只取决于昨天。

js
var maxProfit = function(k, prices) {
    // 就是把3 的两个变量拓展到K 个

    // buy表示第k次买入的利润,初始是负无穷
    let buy = new Array(k+1).fill(-Infinity);
    // sell表示第 k 次卖出的利润,初始是 0;
    let sell = new Array(k+1).fill(0);

    for(let i=0;i<prices.length;i++){
        const price = prices[i];
        // buy 必须从 1 开始啊
        for(let j=1;j<=k;j++){
            // 就上次卖出后的利润减去这次的售价
            buy[j] = Math.max(buy[j], sell[j-1]-price);
            // 这次的利润加上这次的价格
            sell[j] = Math.max(sell[j], buy[j]+price);
        }
    }
    return sell[k];
};
  1. 买卖股票的最佳时机 V https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-v/

怎么 tm 还有做空啊

js
本站访客数 人次 本站总访问量