mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #758 from Jerry-306/patch-6
0122 买卖股票最佳时机ⅱ 添加 js 版本 滚动数组 解法
This commit is contained in:
@ -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;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user