mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
feat(0309): 另一种状态定义思路
This commit is contained in:
@ -359,6 +359,26 @@ func max(a, b int) int {
|
||||
|
||||
### Javascript:
|
||||
|
||||
> 不同的状态定义 感觉更容易理解些
|
||||
```javascript
|
||||
function maxProfit(prices) {
|
||||
// 第i天状态 持股 卖出 非冷冻期(不持股) 处于冷冻期
|
||||
const dp = new Array(prices.length).fill(0).map(() => [0, 0, 0, 0]);
|
||||
dp[0][0] = -prices[0];
|
||||
for (let i = 1; i < prices.length; i++) {
|
||||
// 持股
|
||||
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][2] - prices[i]);
|
||||
// 卖出
|
||||
dp[i][1] = dp[i - 1][0] + prices[i];
|
||||
// 非冷冻期(不持股)
|
||||
dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1]);
|
||||
// 冷冻期(上一天卖出)
|
||||
dp[i][3] = dp[i - 1][1];
|
||||
}
|
||||
return Math.max(...dp.pop());
|
||||
};
|
||||
```
|
||||
|
||||
```javascript
|
||||
const maxProfit = (prices) => {
|
||||
if(prices.length < 2) {
|
||||
|
Reference in New Issue
Block a user