添加0123.买卖股票的最佳时机III和Java版本

This commit is contained in:
wzs
2021-05-12 23:23:13 +08:00
parent afaca167dc
commit 7123ab8244

View File

@ -190,9 +190,42 @@ dp[1] = max(dp[1], dp[0] - prices[i]); 如果dp[1]取dp[1],即保持买入股
## 其他语言版本 ## 其他语言版本
Java Java
```java
class Solution { // 动态规划
public int maxProfit(int[] prices) {
// 可交易次数
int k = 2;
// [天数][交易次数][是否持有股票]
int[][][] dp = new int[prices.length][k + 1][2];
// 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]);
}
}
int res = 0;
for (int i = 1; i < 3; i++) {
res = Math.max(res, dp[prices.length - 1][i][0]);
}
return res;
}
}
```
Python Python