Explorar el Código

add 'Best Time to Buy and Sell Stock II' optimize

tangs hace 5 años
padre
commit
6323b2aa21
Se han modificado 1 ficheros con 48 adiciones y 0 borrados
  1. 48 0
      tags/greedy/bestTimeToBuyAndSellStock2/main_optimize.go

+ 48 - 0
tags/greedy/bestTimeToBuyAndSellStock2/main_optimize.go

@@ -0,0 +1,48 @@
+package main
+
+import "fmt"
+
+func main() {
+	var prices []int
+
+	prices = []int{7}
+	fmt.Println(maxProfit(prices))
+
+	prices = []int{7, 8}
+	fmt.Println(maxProfit(prices))
+
+	prices = []int{7, 6}
+	fmt.Println(maxProfit(prices))
+
+	prices = []int{2, 3, 3}
+	fmt.Println(maxProfit(prices))
+
+	prices = []int{7, 4, 2, 5, 7, 2, 3}
+	fmt.Println(maxProfit(prices))
+
+	prices = []int{7, 1, 5, 3, 6, 4}
+	fmt.Println(maxProfit(prices))
+
+	prices = []int{1, 2, 3, 4, 5}
+	fmt.Println(maxProfit(prices))
+
+	prices = []int{7, 6, 4, 3, 1}
+	fmt.Println(maxProfit(prices))
+
+	prices = []int{3, 3, 5, 0, 0, 3, 1, 4}
+	fmt.Println(maxProfit(prices))
+
+}
+
+func maxProfit(prices []int) int {
+	var profit int
+	for i := 0; i < len(prices); i++ {
+		if i == 0 {
+			continue
+		}
+		if prices[i] > prices[i-1] {
+			profit += prices[i] - prices[i-1]
+		}
+	}
+	return profit
+}