diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 5dfe3f0e..c324d392 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -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; +} ```