Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
Return the maximum profit you can make.
Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
还是买卖股票的问题,不同于122题,加了一个条件,就是可以无限次买卖一支股票,但是每次卖的时候要有手续费,在有手续费的情况下考虑最大收益
思路:
因为每次卖出要手续费,所以不能看到有收益就交易了
这里需要考虑较小点买入,较大点卖出,还有手续费
参考309的with cool down的思路dp。
dp的话本来是定义两个数组,但是为了节省space,只定义两个变量
定义一个hold,即较小点买入股票,持有股票的profit
一个cash,较大点卖出股票后转化的cash流,卖出的时候要减去手续费
持有的情况,hold[0] = -prices[0],因为要拿prices[0]的cash去买,所以收益就是-prices[0],后面再持续更新
cash[0]=0,刚开始买卖同一价格不仅没有profit,还会倒贴手续费,所以选择不交易,即0
hold:
买入股票的话相当于hold[i] = cash - prices[i]
不买的话保留hold[i - 1]
取两者较大的
cash:
卖出的话相当于hold[i] + prices[i] - fee
不交易的话就保留cash[i - 1]
取两者较大的
最后返回cash
public int maxProfit(int[] prices, int fee) {
if(prices ==null || prices.length == 0) {
return 0;
}
int cash = 0;
int hold = -prices[0];
for (int i = 1; i < prices.length; i++) {
cash = Math.max(cash, hold + prices[i] - fee);
hold = Math.max(hold, cash - prices[i]);
}
return cash;
}