Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1136 from patchearth/master
Browse files Browse the repository at this point in the history
添加0309.最佳买卖股票时机含冷冻期js空间优化版本
  • Loading branch information
youngyangyang04 committed Mar 22, 2022
2 parents 81ce479 + 70ea2c7 commit df03d48
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions problems/0309.最佳买卖股票时机含冷冻期.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,24 @@ const maxProfit = (prices) => {
};
```

```javascript
// 一维数组空间优化
const maxProfit = (prices) => {
const n = prices.length
const dp = new Array(4).fill(0)
dp[0] = -prices[0]
for (let i = 1; i < n; i ++) {
const temp = dp[0] // 缓存上一次的状态
const temp1 = dp[2]
dp[0] = Math.max(dp[0], Math.max(dp[3] - prices[i], dp[1] - prices[i])) // 持有状态
dp[1] = Math.max(dp[1], dp[3]) // 今天不操作且不持有股票
dp[2] = temp + prices[i] // 今天卖出股票
dp[3] = temp1 // 冷冻期
}
return Math.max(...dp)
};
```


-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit df03d48

Please sign in to comment.