Skip to content

Commit bc77968

Browse files
committed
新增 0188.买卖股票的最佳时机IV.md Go解法
1 parent 5483a71 commit bc77968

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

problems/0188.买卖股票的最佳时机IV.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,41 @@ class Solution:
275275
return dp[2*k]
276276
```
277277
Go:
278+
版本一:
279+
```go
280+
// 买卖股票的最佳时机IV 动态规划
281+
// 时间复杂度O(kn) 空间复杂度O(kn)
282+
func maxProfit(k int, prices []int) int {
283+
if k == 0 || len(prices) == 0 {
284+
return 0
285+
}
286+
287+
dp := make([][]int, len(prices))
288+
status := make([]int, (2 * k + 1) * len(prices))
289+
for i := range dp {
290+
dp[i] = status[:2 * k + 1]
291+
status = status[2 * k + 1:]
292+
}
293+
for j := 1; j < 2 * k; j += 2 {
294+
dp[0][j] = -prices[0]
295+
}
296+
297+
for i := 1; i < len(prices); i++ {
298+
for j := 0; j < 2 * k; j += 2 {
299+
dp[i][j + 1] = max(dp[i - 1][j + 1], dp[i - 1][j] - prices[i])
300+
dp[i][j + 2] = max(dp[i - 1][j + 2], dp[i - 1][j + 1] + prices[i])
301+
}
302+
}
303+
return dp[len(prices) - 1][2 * k]
304+
}
305+
306+
func max(a, b int) int {
307+
if a > b {
308+
return a
309+
}
310+
return b
311+
}
312+
```
278313

279314

280315
Javascript:

0 commit comments

Comments
 (0)