你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
(每次交易:买入+卖出,一个回合)
输入: 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.
public int maxProfit(int[] prices, int fee) {
if(prices == null) return 0;
int len = prices.length;
if(len == 0) return 0;
//定义dp[i][0,1]:0表示不持股,1表示持股
int[][] dp = new int[len][2];
dp[0][0] = 0;//不持股
dp[0][1] =- prices[0];//持股
for(int i = 1; i < len; i ++) {
//不持股
//第i-1天不持股,第i天仍不持股
//第i-1天持股,第i天卖出,所以不持股
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
//持股
//第i-1天持股,第i天也持股
//第i-1天不持股,第i天买入
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return Math.max(dp[len - 1][0], dp[len - 1][1]);
}