-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
review300: best time to buy and sell stock4
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package main | ||
|
||
import "math" | ||
|
||
func maxProfit(k int, prices []int) int { | ||
dpHold := make([]int, len(prices)+1) | ||
dpProfit := make([]int, len(prices)+1) | ||
dpHold[0] = math.MinInt32 | ||
dpProfit[0] = 0 | ||
max := func(a, b int) int { | ||
if a > b { | ||
return a | ||
} | ||
return b | ||
} | ||
for k > 0 { | ||
for i := range prices { | ||
// dpProfit[i+1], 只能使用k-1轮的盈利 | ||
// 不能使用dpProfit[i], 前面交易盈利, 单次交易 | ||
dpHold[i+1] = max(dpHold[i], dpProfit[i+1]-prices[i]) | ||
dpProfit[i+1] = max(dpProfit[i], prices[i]+dpHold[i]) | ||
} | ||
|
||
k-- | ||
} | ||
return dpProfit[len(prices)] | ||
} |