309. Best Time to Buy and Sell Stock with Cooldown

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;

// 定义 dp[i][j] 表示第 i 天休市时处于 j 状态的最大利润
// j = 0: 未购买过
// j = 1: 买入
// j = 2: 卖出
// j = 3: 卖出后的冷冻期
int[][] dp = new int[n][4];
dp[0][0] = 0;
dp[0][1] = -prices[0];
dp[0][2] = 0;
dp[0][3] = 0;

for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0];
dp[i][1] = Math.max(dp[i - 1][1], Math.max(dp[i - 1][0], dp[i - 1][3]) - prices[i]);
dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
dp[i][3] = dp[i - 1][2];
}

return Math.max(dp[n - 1][2], dp[n - 1][3]); // 注意因为含有冷冻期,所以同一天不能买卖多次,所以最大值不一定在 dp[n - 1][3]
}
}

References

309. Best Time to Buy and Sell Stock with Cooldown