diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index e30fa50a..2f28cf1f 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -335,6 +335,8 @@ func max(a,b int)int { JavaScript: +> 动态规划 + ```javascript const maxProfit = prices => { const len = prices.length; @@ -353,7 +355,19 @@ const maxProfit = prices => { }; ``` +> 贪心法 +```javascript +var maxProfit = function(prices) { + let lowerPrice = prices[0];// 重点是维护这个最小值(贪心的思想) + let profit = 0; + for(let i = 0; i < prices.length; i++){ + lowerPrice = Math.min(lowerPrice, prices[i]);// 贪心地选择左面的最小价格 + profit = Math.max(profit, prices[i] - lowerPrice);// 遍历一趟就可以获得最大利润 + } + return profit; +}; +``` -----------------------