1、前言
题目描述2、思路
再次购买股票之前需要出售原先购买的股票,并且还要冷冻一天,也就是更改一下原来的状态转移方程,主要改买入的方程,则方程为:
- dp[n][k][0] = max {dp[n - 1][k][0], dp[n - 1][k][1] + price[n]}
- dp[n][k][1] = max {dp[n - 1][k][1], dp[n - 2][k - 1][0] price[n]}
3、代码
public class SellStockWithCooldown {
public int maxProfit(int[] prices) {
int n = prices.length;
int[][] dp = new int[n][2];
for(int i = 0; i < n; i++){
if(i - 1 == -1){
dp[i][0] = 0;
dp[i][1] = -prices[i];
continue;
}else if(i - 2 == -1){
dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
dp[i][1] = Math.max(dp[i-1][1], -prices[i]);
continue;
}
dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
dp[i][1] = Math.max(dp[i-1][1], dp[i-2][0] - prices[i]);
}
return dp[n - 1][0];
}
public static void main(String[] args) {
int[] prices = new int[]{1,2,3,0,2};
System.out.println(new SellStockWithCooldown().maxProfit(prices));
}
}
网友评论