题目
给定一个整数数组 prices,其中 prices[i]表示第 i 天的股票价格;整数 fee 代表了交易股票的手续费用。
你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
返回获得利润的最大值。
注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
示例 1:
输入:prices = [1, 3, 2, 8, 4, 9], fee = 2输出:8解释:能够达到的最大利润:在此处买入 prices[0] = 1在此处卖出 prices[3] = 8在此处买入 prices[4] = 4在此处卖出 prices[5] = 9总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8
示例 2:
输入:prices = [1,3,7,5,10,3], fee = 3输出:6
提示:
1 <= prices.length <= 5 * 10^41 <= prices[i] < 5 * 10^40 <= fee < 5 * 10^4解题方法
动态规划
设定动态数组dp0表示持有股票的最大收益,dp1表示不持有股票的最大收益。而手续费发生在买入股票的时候,因此递推公式如下:
时间复杂度O(n),空间复杂度O(1)
C++代码:class Solution {public:int maxProfit(vector<int>& prices, int fee) {int dp0 = -prices[0]-fee;int dp1 = 0;for(int i=1; i<prices.size(); i++) {int tmp = dp0;dp0 = max(dp0, dp1-prices[i]-fee);dp1 = max(dp1, tmp+prices[i]);}return dp1;}};
贪心
贪心规则:卖出股票是立刻以无手续费的形式买入当前股票,持续获利,直至当前股票不再盈利(需要重新以更低的价格加手续费买入)。
时间复杂度O(n),空间复杂度O(1)
C++代码:class Solution {public:int maxProfit(vector<int>& prices, int fee) {int cur = prices[0]+fee;int result = 0;for(int i=1; i<prices.size(); i++) {if(prices[i]+fee < cur) cur = prices[i] + fee;else if(prices[i] > cur) {result += prices[i]-cur;cur = prices[i];}}return result;}};
