Bladeren bron

add 'Best Time to Buy and Sell Stock II'

tangs 5 jaren geleden
bovenliggende
commit
9e492cb37a
1 gewijzigde bestanden met toevoegingen van 71 en 0 verwijderingen
  1. 71 0
      tags/greedy/bestTimeToBuyAndSellStock2/main.go

+ 71 - 0
tags/greedy/bestTimeToBuyAndSellStock2/main.go

@@ -0,0 +1,71 @@
+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 {
+	if len(prices) == 0 {
+		return 0
+	}
+	var profit = 0
+	var own = -1
+	var cursor int = 0
+	for i := 0; i < len(prices); i++ {
+		if i == 0 {
+			continue
+		}
+		if prices[i] < prices[i-1] {
+			if own == -1 {
+				cursor = i
+				continue
+			}
+			profit = profit + prices[i-1] - own
+			own = -1
+			cursor = i
+		}
+		if prices[i] > prices[i-1] {
+			if own == -1 {
+				own = prices[cursor]
+			}
+			if i == len(prices)-1 {
+				profit += prices[i] - own
+				own = -1
+			}
+		}
+	}
+	if own != -1 {
+		profit += prices[len(prices)-1] - own
+	}
+	return profit
+}