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: > 动态规划