Skip to content

Commit 36a4a90

Browse files
committed
新增 0122.买卖股票的最佳时机II(动态规划).md Go解法
1 parent 9b79393 commit 36a4a90

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

problems/0122.买卖股票的最佳时机II(动态规划).md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,33 @@ class Solution:
199199
```
200200

201201
Go:
202+
```go
203+
// 买卖股票的最佳时机Ⅱ 动态规划
204+
// 时间复杂度O(n) 空间复杂度O(n)
205+
func maxProfit(prices []int) int {
206+
dp := make([][]int, len(prices))
207+
status := make([]int, len(prices) * 2)
208+
for i := range dp {
209+
dp[i] = status[:2]
210+
status = status[2:]
211+
}
212+
dp[0][0] = -prices[0]
213+
214+
for i := 1; i < len(prices); i++ {
215+
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])
216+
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])
217+
}
218+
219+
return dp[len(prices) - 1][1]
220+
}
221+
222+
func max(a, b int) int {
223+
if a > b {
224+
return a
225+
}
226+
return b
227+
}
228+
```
202229

203230
Javascript:
204231
```javascript

0 commit comments

Comments
 (0)