-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBestTimetoBuyandSellStockwithCooldown.java
More file actions
76 lines (53 loc) · 1.9 KB
/
BestTimetoBuyandSellStockwithCooldown.java
File metadata and controls
76 lines (53 loc) · 1.9 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package recursion_and_dynamic_programming;
/**
* @Author: Wenhang Chen
* @Description:给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
* <p>
* 设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
* <p>
* 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
* 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
* 示例:
* <p>
* 输入: [1,2,3,0,2]
* 输出: 3
* 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
* @Date: Created in 9:10 3/16/2020
* @Modified by:
*/
public class BestTimetoBuyandSellStockwithCooldown {
// dp核心:状态机
public int maxProfit(int[] prices) {
int len = prices.length;
// 特判
if (len < 2) {
return 0;
}
int[][] dp = new int[len][3];
// 0 表示不持股;
// 1 表示持股;
// 2 表示处在冷冻期。
// 初始化
dp[0][0] = 0;
dp[0][1] = -prices[0];
dp[0][2] = 0;
for (int i = 1; i < len; i++) {
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 - 1][2] - prices[i]);
dp[i][2] = dp[i - 1][0];
}
return Math.max(dp[len - 1][0], dp[len - 1][2]);
}
// public int maxProfit(int[] prices) {
// int n = prices.length;
// int dp_i_0 = 0, dp_i_1 = Integer.MIN_VALUE;
// int dp_pre_0 = 0; // 代表 dp[i-2][0]
// for (int i = 0; i < n; i++) {
// int temp = dp_i_0;
// dp_i_0 = Math.max(dp_i_0, dp_i_1 + prices[i]);
// dp_i_1 = Math.max(dp_i_1, dp_pre_0 - prices[i]);
// dp_pre_0 = temp;
// }
// return dp_i_0;
// }
}