File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -275,6 +275,41 @@ class Solution:
275
275
return dp[2 * k]
276
276
```
277
277
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
+ ```
278
313
279
314
280
315
Javascript:
You can’t perform that action at this time.
0 commit comments