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

股票问题是一个动态规划的系列问题,前两题并不难,第三题有难度。

  1. 买卖股票的最佳时机
    视频讲解:https://www.bilibili.com/video/BV1Xe4y1u77q
    https://programmercarl.com/0121.买卖股票的最佳时机.html
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    const dp = new Array(prices.length).fill(0).map(()=>new Array([]))
    dp[0][0] = -prices[0];
    dp[0][1] = 0;
    for (let i=1;i<prices.length;i++) {
        dp[i][0] = Math.max(dp[i-1][0], -prices[i]);
        dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] + prices[i]);
    }

    return dp[prices.length-1][1];
};

122.买卖股票的最佳时机II
视频讲解:https://www.bilibili.com/video/BV1D24y1Q7Ls
https://programmercarl.com/0122.买卖股票的最佳时机II(动态规划).html

可以贪心
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    const dp = new Array(prices.length).fill(0).map(()=>new Array([]));
    dp[0][0] = -prices[0];
    dp[0][1] = 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][1];
};

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

这道题一下子就难度上来了,关键在于至多买卖两次,这意味着可以买卖一次,可以买卖两次,也可以不买卖。
视频讲解:https://www.bilibili.com/video/BV1WG411K7AR
https://programmercarl.com/0123.买卖股票的最佳时机III.html

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
 const len = prices.length;
    const dp = new Array(len).fill(0).map(x => new Array(5).fill(0));
    dp[0][1] = -prices[0];
    dp[0][3] = -prices[0];
    for (let i = 1; i < len; 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 - 1][2] - prices[i]);
        dp[i][4] = Math.max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
    }
    return dp[len - 1][4];
};
posted @ 2024-06-23 23:46  YuanYF6  阅读(1)  评论(0编辑  收藏  举报