123.go 805 B

1234567891011121314151617181920212223242526272829
  1. package main
  2. func maxProfitFor2(prices []int) (profit int) {
  3. if len(prices) <= 1 {
  4. return 0
  5. }
  6. K := 2
  7. dp := make([][]int, K+1) // For k transactions
  8. for i := range dp {
  9. dp[i] = make([]int, len(prices))
  10. }
  11. for k := 1; k <= K; k++ {
  12. tmpMax := dp[k-1][0] - prices[0]
  13. for i := 1; i < len(prices); i++ {
  14. // if not sell stock at day i, dp[k][i] = dp[k][i-1]
  15. // else, dp[k][i] = max(dp[k-1][j] + prices[i] - prices[j]), j in [0, i-1]
  16. // ie. dp[k][i] = prices[i] + max(dp[k-1][j] - prices[j]), j in [0, i-1]
  17. dp[k][i] = maxInt(dp[k][i-1], prices[i]+tmpMax)
  18. tmpMax = maxInt(tmpMax, dp[k-1][i]-prices[i])
  19. profit = maxInt(profit, dp[k][i])
  20. }
  21. }
  22. return
  23. }
  24. // func main() {
  25. // println(maxProfit([]int{3, 3, 5, 0, 0, 3, 1, 4}), 6)
  26. // println(maxProfit([]int{1, 2, 3, 4, 5}), 4)
  27. // }