题目描述
给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。
你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
返回获得利润的最大值。
示例:
输入: 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.
总结
好不容易写了个双99%的DSC
SC除了贪心算法还有动态规划的思想在里面,臭弟弟我就只想着在卖出的时候计算利润。
Sample Code
class Solution {
public int maxProfit(int[] prices, int fee) {
if(prices.length < 2)
return 0;
int profit = 0, min = prices[0];
for(int i = 0; i < prices.length; i++) {
if(prices[i] < min)
min = prices[i];
else if(prices[i] > min + fee){
profit += prices[i] - min - fee;
min = prices[i] - fee;
}
}
return profit;
}
}
Demo & Sample Code
class Solution {
public int maxProfit(int[] prices, int fee) {
if(prices.length < 2) return 0;
int max = Integer.MIN_VALUE;
int min = prices[0];
int res = 0;
for(int i = 1; i < prices.length; i++) {
if(prices[i] > max) max = prices[i];
if(prices[i] < max-fee) { //可以不换min,加不加看情况,加了就得换min
// System.out.println("1 max:"+max+" ,min:"+min);
if(max-min > fee) {
res += max-min-fee;
min = prices[i];
max = -1;
continue;
}
}
if(prices[i] < min) { //必须换min,加不加看情况
// System.out.println("2 max:"+max+" ,min:"+min);
if(max-min > fee)
res += max-min-fee;
min = prices[i];
max = -1;
}
}
// System.out.println("3 max:"+max+" ,min:"+min);
if(max-min > fee) res += max-min-fee;
return res;
}
}
/*
fee=2
3749
4<-->2+2
*/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee