Parcourir la source

add 'Gas Station'

tangs il y a 5 ans
Parent
commit
2bf5ae3645
1 fichiers modifiés avec 38 ajouts et 0 suppressions
  1. 38 0
      tags/greedy/gasStation/main.go

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

@@ -0,0 +1,38 @@
+package main
+
+import "fmt"
+
+func main() {
+	var gas []int
+	var cost []int
+
+	gas = []int{2, 3, 4}
+	cost = []int{3, 4, 3}
+	fmt.Println(canCompleteCircuit(gas, cost))
+
+	gas = []int{1, 2, 3, 4, 5}
+	cost = []int{3, 4, 5, 1, 2}
+	fmt.Println(canCompleteCircuit(gas, cost))
+
+	gas = []int{5, 1, 2, 3, 4}
+	cost = []int{4, 4, 1, 5, 1}
+	fmt.Println(canCompleteCircuit(gas, cost))
+}
+
+func canCompleteCircuit(gas []int, cost []int) int {
+	var restGas, ans = 0, -1
+	var count, index int
+	for i := 0; i < len(gas); i++ {
+		count, restGas, index = 1, gas[i]-cost[i], (i+1)%len(gas)
+		for restGas > 0 && count != (len(gas)) {
+			restGas = restGas + gas[index] - cost[index]
+			index = (index + 1) % len(gas)
+			count++
+		}
+		if restGas >= 0 && count == len(gas) {
+			ans = i
+			break
+		}
+	}
+	return ans
+}