给出每天的股票价格和一个交易费用fee,可以进行任意次交易,问最大收益是多少
sol:
have[i]: 表示第i天持有股票的时候最大收益
notHave[i]: 表示第i不持有股票的最大收益
初始化have[0] = -price[i]; notHave[0] = 0;
转移方程:
have[i] = max(notHave[i-1] -price[i], have[i-1])
notHave[i] = max(notHave[i-1], have[i-1] + price[i] - fee)
public int maxProfit(int[] prices, int fee) {
int[] have = new int[prices.length];
int[] notHave = new int[prices.length];
have[0] = -prices[0];
notHave[0] = 0;
for (int i = 1; i < prices.length; i++) {
have[i] = Math.max(notHave[i - 1] - prices[i], have[i-1]);
notHave[i] = Math.max(notHave[i - 1], have[i - 1] - fee + prices[i]);
}
return notHave[prices.length - 1];
}