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

吞佛童子2022年6月9日小于 1 分钟

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

难度: 🌗

问题描述

img_41.png


解法

class Solution {
    public int maxProfit(int[] prices) {
        // 思路:
        // 可以买卖多次股票,但是任何时刻最多持有一张股票
        int len = prices.length;
        int[][] dp = new int[len][2];
        dp[0][1] = - prices[0];
        for(int i = 1; i < len; i ++) {
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i - 1][0] - prices[i], dp[i - 1][1]); // 关键点
        }
        return dp[len - 1][0];
    }
}

输出

img_40.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou