【LeetCode-714】买卖股票的最佳时机含手续费

问题

给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

返回获得利润的最大值。

注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

示例

输入: prices = [1, 3, 2, 8, 4, 9], fee = 2
输出: 8

解答1:完整状态机

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();
        vector<int> hold(n + 1, INT_MIN);
        vector<int> sold(n + 1, 0);
        for (int i = 1; i <= n; i++) {
            sold[i] = max(sold[i - 1], hold[i - 1] + prices[i - 1]);
            hold[i] = max(hold[i - 1], sold[i - 1] - prices[i - 1] - fee);
        }
        return sold[n];
    }
};

重点思路

只需要在每次买入或者卖出时添加一笔手续费即可,因为有INT_MIN,避免溢出,将手续费设置在买入阶段。

解答2:状态压缩

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int sold = 0, hold = INT_MIN;
        for (int p : prices) {
            sold = max(sold, hold + p);
            hold = max(hold, sold - p - fee);
        }
        return sold;
    }
};

重点思路

状态压缩的分析详见【LeetCode-122】买卖股票的最佳时机 II

posted @ 2021-04-03 20:17  tmpUser  阅读(42)  评论(0编辑  收藏  举报