改进123, 188的Java版本代码

This commit is contained in:
hk27xing
2021-07-08 17:25:57 +08:00
parent fb91b760eb
commit f5dd57cec5
2 changed files with 75 additions and 48 deletions

View File

@@ -193,35 +193,49 @@ dp[1] = max(dp[1], dp[0] - prices[i]); 如果dp[1]取dp[1],即保持买入股
Java
```java
class Solution { // 动态规划
// 版本一
class Solution {
public int maxProfit(int[] prices) {
// 可交易次数
int k = 2;
int len = prices.length;
// 边界判断, 题目中 length >= 1, 所以可省去
if (prices.length == 0) return 0;
// [天数][交易次数][是否持有股票]
int[][][] dp = new int[prices.length][k + 1][2];
/*
* 定义 5 种状态:
* 0: 没有操作, 1: 第一次买入, 2: 第一次卖出, 3: 第二次买入, 4: 第二次卖出
*/
int[][] dp = new int[len][5];
dp[0][1] = -prices[0];
// 初始化第二次买入的状态是确保 最后结果是最多两次买卖的最大利润
dp[0][3] = -prices[0];
// badcase
dp[0][0][0] = 0;
dp[0][0][1] = Integer.MIN_VALUE;
dp[0][1][0] = 0;
dp[0][1][1] = -prices[0];
dp[0][2][0] = 0;
dp[0][2][1] = Integer.MIN_VALUE;
for (int i = 1; i < prices.length; i++) {
for (int j = 2; j >= 1; j--) {
// dp公式
dp[i][j][0] = Math.max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i]);
dp[i][j][1] = Math.max(dp[i - 1][j][1], dp[i - 1][j - 1][0] - prices[i]);
}
for (int i = 1; i < len; i++) {
dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
dp[i][2] = Math.max(dp[i - 1][2], dp[i][1] + prices[i]);
dp[i][3] = Math.max(dp[i - 1][3], dp[i][2] - prices[i]);
dp[i][4] = Math.max(dp[i - 1][4], dp[i][3] + prices[i]);
}
int res = 0;
for (int i = 1; i < 3; i++) {
res = Math.max(res, dp[prices.length - 1][i][0]);
return dp[len - 1][4];
}
}
// 版本二: 空间优化
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int[] dp = new int[5];
dp[1] = -prices[0];
dp[3] = -prices[0];
for (int i = 1; i < len; i++) {
dp[1] = Math.max(dp[1], dp[0] - prices[i]);
dp[2] = Math.max(dp[2], dp[1] + prices[i]);
dp[3] = Math.max(dp[3], dp[2] - prices[i]);
dp[4] = Math.max(dp[4], dp[3] + prices[i]);
}
return res;
return dp[4];
}
}
```