题目:
给定一个整数数组 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来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
思路:
1.类似冷冻期的题目:
手里没有股票:①可能一直没有,不用管手续费;②今天卖出,减去手续费
手里有股票:一直就有;或者今天买入;不用做额外处理
2.当天有:之前一直都有;之前没有,买了一股
当天没有:之前一直都没有;之前有,卖了,需要交手续费!
3. 贪心:假装购买和假装出售:
if和else if判断,保证了:
有利可图时,才真正的购买;
下次再购买的 价格加手续费,能使当前卖掉还有利可图时,才真正卖掉!
代码:
1. 参考122-冷冻期的情况:效率最差
代码能跑,但是很差;
class Solution {
public int maxProfit(int[] prices, int fee) {
if(prices == null || prices.length == 0 || prices.length == 1) return 0;
int len = prices.length;
int[] dp = new int[3];
dp[0] = -prices[0];
dp[1] = 0;
dp[2] = -2;//这里表示:买了又卖了
//只有卖出时,才会交手续费
for(int i = 1;i < len;i++){
dp[0] = Math.max(Math.max(dp[0],dp[1] - prices[i]),dp[2] - prices[i]);
dp[1] = Math.max(dp[1],dp[2]);
dp[2] = dp[0] + prices[i] - fee;
}
return Math.max(dp[1],dp[2]);
}
}
2. 简单的方式:将手里没有股票的状态合起来
class Solution {
public int maxProfit(int[] prices, int fee) {
int dp0 = 0;
int dp1 = -prices[0];
for(int i = 1;i < prices.length;i++){
dp0 = Math.max(dp0,dp1 + prices[i] - fee);//此时的dp1已经是 买过股票之后的情况
dp1 = Math.max(dp1,dp0 - prices[i]);
}
return dp0;
}
}
3. 贪心:多次交易就要多掏手续费!尽量少交易
class Solution {
public int maxProfit(int[] prices, int fee) {
//贪心:将fee加在买股票的支出中,想要利润最大,卖了就要卖;要么不买
if(prices == null || prices.length == 0 || prices.length == 1) return 0;
int maxProfit = 0;
int buy = prices[0] + fee;//买股票要花的钱
for(int i = 1;i < prices.length;i++){
if(prices[i] + fee < buy){
buy = prices[i] + fee;
}
else if(prices[i] > buy){//此时是可以卖的
maxProfit += prices[i] - buy;//此时是这次卖掉的收益,这次交易的手续费也已经包含!
buy = prices[i];//其实不一定真的卖掉了!但是表示是可以卖的!
}
}
return maxProfit;
}
}