dengxinyi 6 vuotta sitten
vanhempi
commit
aa5cfddbca
2 muutettua tiedostoa jossa 42 lisäystä ja 5 poistoa
  1. 25 5
      hard/123.go
  2. 17 0
      hard/124.go

+ 25 - 5
hard/123.go

@@ -1,9 +1,29 @@
 package main
 
-func maxProfit(prices []int) int {
-	return 0
+func maxProfit(prices []int) (profit int) {
+	if len(prices) <= 1 {
+		return 0
+	}
+	K := 2
+	dp := make([][]int, K+1) // For k transactions
+	for i := range dp {
+		dp[i] = make([]int, len(prices))
+	}
+	for k := 1; k <= K; k++ {
+		tmpMax := dp[k-1][0] - prices[0]
+		for i := 1; i < len(prices); i++ {
+			// if not sell stock at day i, dp[k][i] = dp[k][i-1]
+			// else, dp[k][i] = max(dp[k-1][j] + prices[i] - prices[j]), j in [0, i-1]
+			// ie. dp[k][i] = prices[i] + max(dp[k-1][j] - prices[j]), j in [0, i-1]
+			dp[k][i] = maxInt(dp[k][i-1], prices[i]+tmpMax)
+			tmpMax = maxInt(tmpMax, dp[k-1][i]-prices[i])
+			profit = maxInt(profit, dp[k][i])
+		}
+	}
+	return
 }
 
-func main() {
-
-}
+// func main() {
+// 	println(maxProfit([]int{3, 3, 5, 0, 0, 3, 1, 4}), 6)
+// 	println(maxProfit([]int{1, 2, 3, 4, 5}), 4)
+// }

+ 17 - 0
hard/124.go

@@ -0,0 +1,17 @@
+package main
+
+/**
+ * Definition for a binary tree node.
+ * type TreeNode struct {
+ *     Val int
+ *     Left *TreeNode
+ *     Right *TreeNode
+ * }
+ */
+func maxPathSum(root *TreeNode) int {
+	return 0
+}
+
+func main() {
+
+}