题目描述
给定一个整数数组 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.
方法一:
可以使用“最佳买卖股票时机含冷冻期”中的方法,有两个状态,buy[i]和sell[i] ,区别是:
1.没有冷冻期,所以可以在第i-1天卖出之后,在第i天继续买
2.卖出股票的时候需要减去手续费
class Solution {
public int maxProfit(int[] prices, int fee) {
int len = prices.length;
if(len <= 1){
return 0;
}
int buy[] = new int[len];
int sell[] = new int[len];
buy[0] = -prices[0];
sell[0] = 0;
buy[1] = Math.max(buy[0],-prices[1]);
sell[1] = Math.max(sell[0],buy[0]+prices[1]-fee);
for(int i = 2;i<len;i++){
buy[i] = Math.max(buy[i-1],sell[i-1]-prices[i]);
sell[i] = Math.max(sell[i-1],buy[i-1]+prices[i]-fee);
}
return sell[len-1];
}
}
方法二:
与上面的思路一样,但是只有两个变量,buy和sell
class Solution {
public int maxProfit(int[] prices, int fee) {
int buy = -prices[0];
int sell = 0;
for(int i = 1;i < prices.length;i++){
sell = Math.max(sell,buy+prices[i]-fee);
buy = Math.max(buy,sell - prices[i]);
}
return sell;
}
}