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

动态规划

class Solution {
    public int maxProfit(int[] prices, int fee) {

        int[][] dp = new int[prices.length][2];

        dp[0][0] = -prices[0];

        /**
         * 和《122. 买卖股票的最佳时机II》相比只有一处不同
         * 总共有2种状态
         * dp[i][0]:持有股票(可能是之前买的,可能是今天买的)
         * dp[i][1]:不持有股票(可能是之前卖的,可能是今天卖的,如果是今天卖,要扣掉手续费)
         */
        for (int 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] - fee);
        }

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

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

贪心

class Solution {
    public int maxProfit(int[] prices, int fee) {

        /**
         * 贪心思想可以浓缩成一句话,即当我们卖出一支股票时,我们就立即获得了以相同价格并且免除手续费买入一支股票的权利
         * 遍历数组,记录购买股票的最小成本(本金加手续费)
         */
        int cost = prices[0] + fee;
        int sum = 0;

        for (int i = 1; i < prices.length; i++) {

            /**
             * 遇到更小的成本就更新
             * 如果今天的价格大于成本,就将其卖掉,但是不能确定明天是否会继续上涨(如果明天继续上涨,那今天卖就多出了一份手续费)
             * 因此可以假设明天会上涨,那今天卖掉,今天再买,但成本设置为扣掉手续费,然后明天再卖。因为总共只出了一份手续费,这样就等价于今天没卖,明天再卖(相当于一个反悔操作)
             * 如果明天没有上涨,那今天卖掉以后不再买,成本怎么设置不影响,继续寻找更小的成本
             */
            if (prices[i] + fee < cost){
                cost = prices[i] + fee;
            }
            else if (prices[i] > cost){

                sum += prices[i] - cost;
                cost = prices[i];
            }
        }

        return sum;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/

posted @ 2022-02-27 10:22  振袖秋枫问红叶  阅读(48)  评论(0)    收藏  举报