From 0e1cbda7153b3b5b2892110696f10afe7833a38f Mon Sep 17 00:00:00 2001 From: "Neil.Liu" <88214924@qq.com> Date: Fri, 8 Apr 2022 23:56:49 +0800 Subject: [PATCH] =?UTF-8?q?Update=200121.=E5=8D=96=E8=82=A1=E7=A5=A8?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA.md=20=E8=B4=AA?= =?UTF-8?q?=E5=BF=83=E4=BB=A5=E5=8F=8A=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92?= =?UTF-8?q?=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0121.买卖股票的最佳时机.md | 52 ++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index e7c0ac65..f0bc3b97 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -311,7 +311,36 @@ class Solution: ``` Go: +> 贪心法: +```Go +func maxProfit(prices []int) int { + low := math.MaxInt32 + rlt := 0 + for i := range prices{ + low = min(low, prices[i]) + rlt = max(rlt, prices[i]-low) + } + return rlt +} +func min(a, b int) int { + if a < b{ + return a + } + + return b +} + +func max(a, b int) int { + if a > b{ + return a + } + + return b +} +``` + +> 动态规划:版本一 ```Go func maxProfit(prices []int) int { length:=len(prices) @@ -338,6 +367,29 @@ func max(a,b int)int { } ``` +> 动态规划:版本二 +```Go +func maxProfit(prices []int) int { + dp := [2][2]int{} + dp[0][0] = -prices[0] + dp[0][1] = 0 + for i := 1; i < len(prices); i++{ + dp[i%2][0] = max(dp[(i-1)%2][0], -prices[i]) + dp[i%2][1] = max(dp[(i-1)%2][1], dp[(i-1)%2][0]+prices[i]) + } + + return dp[(len(prices)-1)%2][1] +} + +func max(a, b int) int { + if a > b{ + return a + } + + return b +} +``` + JavaScript: > 动态规划