代码随想录算法训练营第四十一天| 121. 买卖股票的最佳时机 、 122.买卖股票的最佳时机II 、 123.买卖股票的最佳时机III

29 阅读1分钟

121. 买卖股票的最佳时机

相关链接:题目链接文章讲解 视频讲解

解题思路

代码实现

var maxProfit = function(prices) {
    var dp = new Array(prices.length).fill(0).map((item)=>new Array(2).fill(0));
    console.log(dp)
    //不持有                
    dp[0][0] =0;
    // 持有
    dp[0][1] = -prices[0];                         
    for(let i =1;i<prices.length;i++){
        dp[i][1]= Math.max(dp[i-1][1] , 0 - prices[i]);
        dp[i][0] = Math.max(dp[i-1][0],dp[i][1]+prices[i]);
    }
    return  dp[prices.length-1][0]
                                    
};

122.买卖股票的最佳时机II

相关链接:题目链接文章讲解 视频讲解

解题思路

代码实现

var maxProfit = function(prices) {
    var dp = new Array(prices.length).fill(0).map(()=>new Array(2).fill(0));
    // 不持有
    dp[0][0] = 0;
    dp[0][1]= -prices[0];

    for(let i=1;i<prices.length;i++){
        dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
        dp[i][1]= Math.max(dp[i-1][1], dp[i-1][0]-prices[i]);
    }
    return dp[prices.length-1][0]
};

123.买卖股票的最佳时机III

相关链接:题目链接文章讲解 视频讲解

解题思路

代码实现

var maxProfit = function(prices) {
    var dp = new Array(prices.length).fill(0).map(()=>new Array(5).fill(0));

    // dp[i][0] // 表示没
    // dp[i][1] // 第一次买入
    // dp[i][2] // 第一次卖出
    // dp[i][3] // 第二次买入
    // dp[i][4]  // 第二次卖出
    dp[0][0] = 0;
    dp[0][1] = -prices[0];
    dp[0][2] = 0;
    dp[0][3] = -prices[0];
    dp[0][4] = 0;

    for(let i =1;i<prices.length;i++){
        dp[i][0] = dp[i-1][0];
        dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]);
        dp[i][2] = Math.max(dp[i-1][2],dp[i-1][1] + prices[i]);
        dp[i][3] = Math.max(dp[i-1][3], dp[i][2] - prices[i]);
        dp[i][4] = Math.max(dp[i-1][4],dp[i][3] + prices[i]);
    }
    return dp[prices.length-1][4];
};