1.题目描述:
给定一个整数数组prices,其中prices[i]表示第i天的股票价格;整数fee代表了交易股票的手续费用。你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。返回获得利润的最大值。注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
2.贪心算法:
题目与leetcode122. 买卖股票的最佳时机 II类似,但是多了一次手续费,按照原来方法算会出现问题。比如1,5,6,9按照原来方法获利9 - 6 + 6 - 5 + 5 - 1 = 8,如果手续2,其实只需要一次手续9 - 1 - 2 = 6,循环判断比1(前面最小的数)大fee的数就是可以卖的数,但是手续只有一次,5 - 1 + 9 - 5 - 2 = 6。
class Solution {
public int maxProfit(int[] prices, int fee) {
int res = 0;
int min = Integer.MAX_VALUE;
for (int i = 0; i < prices.length - 1; i++) {
min = Math.min(prices[i] + fee, min);//又更低价的则更新为更低价的,比如6改为1
if(prices[i + 1] > min) {
res += prices[i + 1] - min;
min = prices[i + 1];//非真正出售,更新min,最终得到(5-1)+(9-5),手续只有一次
}
}
return res;
}
}
3.动态规划:
动态规划能解决一系列股票问题,贪心只能解决一部分并且不容易理解,这题解法与leetcode122. 买卖股票的最佳时机 II几乎一样,在dp[i][0]不持有股票中当天卖出的情况中扣除手续费即可。
class Solution {
public int maxProfit(int[] prices, int fee) {
if (prices.length == 1) return 0;
int[][] dp = new int[prices.length][2];
//dp[i][0]代表不持有股票
//dp[i][1]代表持有股票
dp[0][1] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);//i-1就不持有和i天卖出
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);//i-1就持有和i天买入
}
return dp[dp.length - 1][0];
}
}