| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -0,0 +1,33 @@ | |||
| 1 | + /** | ||
| 2 | + * @param {number[]} prices | ||
| 3 | + * @return {number} | ||
| 4 | + */ | ||
| 5 | + /* | ||
| 6 | + 设sell[i] 第i天卖出操作的最大利润 | ||
| 7 | + buy[i] 第i天买进操作的最大利润 | ||
| 8 | + | ||
| 9 | + 所以,显然有状态转移方程 | ||
| 10 | + buy[i] = max(buy[i-1] , sell[i-2] – prices[i]) // 休息一天在买入,所以是sell[i-2]在状态转移 | ||
| 11 | + sell[i] = max(sell[i-1], buy[i-1] + prices[i]) | ||
| 12 | + 最后显然有sell[n-1] > buy[n-1] 所以我们返回sell[n-1] | ||
| 13 | + */ | ||
| 14 | + var maxProfit = function (prices) { | ||
| 15 | + if (prices.length === 0) { | ||
| 16 | + return 0; | ||
| 17 | + } | ||
| 18 | + | ||
| 19 | + var buy = new Array(prices.length).fill(0); | ||
| 20 | + var sell = new Array(prices.length).fill(0); | ||
| 21 | + | ||
| 22 | + buy[0] = -prices[0]; | ||
| 23 | + buy[1] = Math.max(-prices[0], -prices[1]); | ||
| 24 | + sell[0] = 0; | ||
| 25 | + sell[1] = prices[1] - prices[0]; | ||
| 26 | + | ||
| 27 | + for (var i = 2; i < prices.length; i++) { | ||
| 28 | + buy[i] = Math.max(sell[i - 2] - prices[i], buy[i - 1]); | ||
| 29 | + sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]); | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + return sell[prices.length - 1]; | ||
| 33 | + }; | ||
| Back | FazBrowse Home | New Git URL |
0 commit comments