mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Merge pull request #1136 from patchearth/master
添加0309.最佳买卖股票时机含冷冻期js空间优化版本
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user