javascript算法题-动态规划-买卖股票的最佳时机I/II/III

129 阅读1分钟

121. [买卖股票的最佳时机](121. 买卖股票的最佳时机 - 力扣(LeetCode))

image.png

初始化二维数组

// let dp[len1][len2] = {0};
const dp = new Array(len1 + 1).fill(0).map(() => new Array(len2 + 1).fill(0));

let dp = []
for(let i = 0;i<prices.length;i++){
    dp.push([])
}

调用max函数

// dp[i][j] = max(dp[i][j-1],dp[i-1][j]) //那就左边或者上边最大值
dp[i][j] = Math.max(dp[i][j-1],dp[i-1][j]) //那就左边或者上边最大值

题解

image.png

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let len = prices.length
    // let dp = new Array(len+1).fill(0).map(()=>new Array(len+1).fill(0)) // 会有报错
    let dp = []
    for(let i = 0;i<prices.length;i++){
        dp.push([])
    }
    dp[0][0] = -prices[0]
    dp[0][1] = 0

    for(let i = 1 ; i < len ; 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[len-1][1];
};

122. [买卖股票的最佳时机 II](122. 买卖股票的最佳时机 II - 力扣(LeetCode))

image.png

题解

image.png

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let dp = []
    for(let i = 0 ; i < prices.length ; i++){
        dp.push([])
    }
    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](123. 买卖股票的最佳时机 III - 力扣(LeetCode))

image.png

题解

image.png

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let dp = []
    for(let i = 0 ; i < prices.length ; i ++){
        dp.push([])
    }
    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][0] - prices[i])
        dp[i][2] = Math.max(dp[i-1][2],dp[i][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]
};