Given an integer array prices, where the i-th element represents the stock price on the i-th day; a non-negative integer fee represents the transaction fee for stocks.
You can complete transactions an unlimited number of times, but you need to pay a handling fee for each transaction. If you have already purchased a stock, you can no longer buy stocks before you sell it.
Returns the maximum profit obtained.
Note: A transaction here refers to the entire process of buying, holding and selling stocks. You only need to pay a handling fee for each transaction.
Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: Maximum profit that can be achieved:
buy here prices[0] = 1
sell here prices[ 3] = 8
Buy here prices[4] = 4
Sell here prices[5] = 9
Total profit: ((8-1)-2) + ((9-4)-2) = 8 .
Note:
0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.
public int maxProfit(int[] prices, int fee) {
int len = prices.length;
if(len <= 1) return 0;
int hv = -prices[0] - fee;//持有股票
int hs = 0;//没有持有股票
for(int i = 1; i < len; i++) {
hv = Math.max(hv, hs - prices[i] - fee);//持有股票
hs = Math.max(hs, hv + prices[i]);//没有持有股票
}
return hs;
}