Просмотр исходного кода

add 'Valid Parentheses' optimize

tangs 5 лет назад
Родитель
Сommit
3580fb9e18
2 измененных файлов с 48 добавлено и 0 удалено
  1. 4 0
      tags/greedy/gasStation/main.go
  2. 44 0
      tags/greedy/gasStation/main_optimze.go

+ 4 - 0
tags/greedy/gasStation/main.go

@@ -17,6 +17,10 @@ func main() {
 	gas = []int{5, 1, 2, 3, 4}
 	cost = []int{4, 4, 1, 5, 1}
 	fmt.Println(canCompleteCircuit(gas, cost))
+
+	gas = []int{1, 4, 6, 3, 2}
+	cost = []int{3, 4, 5, 1, 2}
+	fmt.Println(canCompleteCircuit(gas, cost))
 }
 
 func canCompleteCircuit(gas []int, cost []int) int {

+ 44 - 0
tags/greedy/gasStation/main_optimze.go

@@ -0,0 +1,44 @@
+package main
+
+import "fmt"
+
+func main() {
+	var gas []int
+	var cost []int
+
+	// -1
+	gas = []int{2, 3, 4}
+	cost = []int{3, 4, 3}
+	fmt.Println(canCompleteCircuit(gas, cost))
+
+	// 3
+	gas = []int{1, 2, 3, 4, 5}
+	cost = []int{3, 4, 5, 1, 2}
+	fmt.Println(canCompleteCircuit(gas, cost))
+
+	// 4
+	gas = []int{5, 1, 2, 3, 4}
+	cost = []int{4, 4, 1, 5, 1}
+	fmt.Println(canCompleteCircuit(gas, cost))
+
+	// 1
+	gas = []int{1, 4, 6, 3, 2}
+	cost = []int{3, 4, 5, 1, 2}
+	fmt.Println(canCompleteCircuit(gas, cost))
+}
+
+func canCompleteCircuit(gas []int, cost []int) int {
+	var sum, current, index = 0, 0, 0
+	for i := 0; i < len(gas); i++ {
+		sum += gas[i] - cost[i]
+		current += gas[i] - cost[i]
+		if current < 0 {
+			current = 0
+			index = i + 1
+		}
+	}
+	if sum < 0 {
+		return -1
+	}
+	return index
+}