mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 15:09:40 +08:00
Update 0309.最佳买卖股票时机含冷冻期.md
添加了java版本的另一种解题思路,无需考虑多种状态,还是只考虑持有与未持有两种状态
This commit is contained in:
@ -205,6 +205,29 @@ class Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
```java
|
||||
//另一种解题思路
|
||||
class Solution {
|
||||
public int maxProfit(int[] prices) {
|
||||
int[][] dp = new int[prices.length + 1][2];
|
||||
dp[1][0] = -prices[0];
|
||||
|
||||
for (int i = 2; i <= prices.length; i++) {
|
||||
/*
|
||||
dp[i][0] 第i天未持有股票收益;
|
||||
dp[i][1] 第i天持有股票收益;
|
||||
情况一:第i天是冷静期,不能以dp[i-1][1]购买股票,所以以dp[i - 2][1]买股票,没问题
|
||||
情况二:第i天不是冷静期,理论上应该以dp[i-1][1]购买股票,但是第i天不是冷静期说明,第i-1天没有卖出股票,
|
||||
则dp[i-1][1]=dp[i-2][1],所以可以用dp[i-2][1]买股票,没问题
|
||||
*/
|
||||
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 2][1] - prices[i - 1]);
|
||||
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i - 1]);
|
||||
}
|
||||
|
||||
return dp[prices.length][1];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
|
Reference in New Issue
Block a user