🌗 714. 买卖股票的最佳时机含手续费

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

🌗 714. 买卖股票的最佳时机含手续费

难度: 🌗

问题描述

img_5.png


解法

class Solution {
    public int maxProfit(int[] prices, int fee) {
        // 思路:
        // 未持有 - 持有
        int len = prices.length;
        int[][] dp = new int[len][2];
        // 初始化
        dp[0][1] = - prices[0] - fee; // 可以在买入时减去 fee,也可以在卖出时减去
        // dp
        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][1], dp[i - 1][0] - prices[i] - fee);
        }
        return dp[len - 1][0];
    }
}

输出

img_4.png

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