Best Time to Buy and Sell Stock with Cooldown
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
- 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
- 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:
输入: [1,2,3,0,2]
输出: 3
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
分析
用两个数组,buy,sell记录第i天位置,前一天采取buy或sell操作时能得到的最大值。
- buy[i] = max(sell[i-2]-price,buy[i-1])
- sell[i] = max(buy[i-1]+price,sell[i-1])
代码
class Solution {
public int maxProfit(int[] prices) {
if(prices.length<2){
return 0;
}else if(prices.length == 2 && prices[0]>=prices[1]){
return 0;
}else if(prices.length == 2 && prices[0]<prices[1])
return prices[1]-prices[0];
int[] buy = new int[prices.length];
int[] sell = new int[prices.length];
int res=Integer.MIN_VALUE;
buy[0] = -prices[0];
buy[1] = -Math.min(prices[0],prices[1]);
sell[1] = Math.max(buy[0]+prices[1],0);
for(int i=2;i<prices.length;i++){
buy[i] = Math.max(sell[i-2]-prices[i],buy[i-1]);
sell[i]= Math.max(buy[i-1]+prices[i],sell[i-1]);
res = sell[i]>res?sell[i]:res;
}
return res;
}
}