题解 | 买卖股票的最好时机(三)

买卖股票的最好时机(三)

https://www.nowcoder.com/practice/4892d3ff304a4880b7a89ba01f48daf9

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 两次交易所能获得的最大收益
 * @param prices int整型一维数组 股票每一天的价格
 * @return int整型
 */
function maxProfit(prices) {
    // write code here
    const n = prices.length;
    // 0 一次都没买
    // 1 买了一次
    // 2 买了一次且卖了一次
    // 3 买了两次
    // 4 都卖了
    const dp = Array.from({length: n}, () => new Array(5).fill(-Infinity))
    let max = 0
    // 0的时候只可能有两种状态
    dp[0][1] = -prices[0]
    dp[0][0] = 0
    for (let i = 1; i < n; 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])
        // 3 买了两次,可能之前就买了两次,或者之前买了一次且卖了一次,现在又买了一次
        dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2] - prices[i])
        // 4 都卖了,可能之前都卖了,或者之前买了两次,卖了一次,当前卖了
        dp[i][4] = Math.max(dp[i - 1][4], dp[i - 1][3] + prices[i])
        max = Math.max(max, dp[i][2], dp[i][4])
    }
    return max
}
module.exports = {
    maxProfit: maxProfit,
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务