0122 买卖股票最佳时机ⅱ 添加 js 版本 滚动数组 解法

This commit is contained in:
Jerry-306
2021-09-17 10:11:52 +08:00
committed by GitHub
parent fbb5991327
commit 65531e6de8

View File

@ -202,6 +202,7 @@ Go
Javascript
```javascript
// 方法一动态规划dp 数组)
const maxProfit = (prices) => {
let dp = Array.from(Array(prices.length), () => Array(2).fill(0));
// dp[i][0] 表示第i天持有股票所得现金。
@ -222,6 +223,21 @@ const maxProfit = (prices) => {
return dp[prices.length -1][0];
};
// 方法二:动态规划(滚动数组)
const maxProfit = (prices) => {
// 滚动数组
// have: 第i天持有股票最大收益; notHave: 第i天不持有股票最大收益
let n = prices.length,
have = -prices[0],
notHave = 0;
for (let i = 1; i < n; i++) {
have = Math.max(have, notHave - prices[i]);
notHave = Math.max(notHave, have + prices[i]);
}
// 最终手里不持有股票才能保证收益最大化
return notHave;
}
```