From da254e87ada310eb98a3d400bc2fc109ba3ef6c8 Mon Sep 17 00:00:00 2001 From: Vl_Coding_lover <1773279395@qq.com> Date: Sun, 10 Oct 2021 16:08:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B00121=20=E4=B9=B0=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA=20?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86JS=E7=89=88=E6=9C=AC=E7=9A=84?= =?UTF-8?q?=E8=B4=AA=E5=BF=83=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 第一次向卡哥的LeetCode-Master提交代码 激动.jpg! 对于这道题 第一次接触这道题的时候使用的暴力解一跑直接超时 后来看了题解中使用的贪心算法惊为天人 觉得好有道理!看到这道题里还没有 就加入了一下~希望以后可以为卡哥的项目共享更多代码! --- problems/0121.买卖股票的最佳时机.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) 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; +}; +``` -----------------------