Skip to content

Instantly share code, notes, and snippets.

@omept
Created July 14, 2022 07:51
Show Gist options
  • Save omept/d5520741b0a10e3683a58e716dd0566e to your computer and use it in GitHub Desktop.
Save omept/d5520741b0a10e3683a58e716dd0566e to your computer and use it in GitHub Desktop.
Gas Station Problem 2
func Execute2() {
gas := []int{1, 5, 3, 3, 5, 3, 1, 3, 4, 5}
cost := []int{5, 2, 2, 8, 2, 4, 2, 5, 1, 2}
sum := 0
tP := 0
prevSum := 0
for i := 0; i < len(gas); i++ {
sum += (gas[i] - cost[i])
if sum < 0 {
tP = i + 1
prevSum = sum
sum = 0
}
}
if tP == len(gas) || prevSum+sum < 0 {
tP = -1
}
fmt.Println(tP)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment