1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| func canCompleteCircuit(gas []int, cost []int) int { for i := 0; i < len(gas); { j, steps, left := i, 0, 0 for steps < len(gas) { if left+gas[j]-cost[j] >= 0 { left += gas[j] - cost[j] steps++ j = getNextIndex(j, len(gas)) } else { break } }
if steps == len(gas) { return i } else { i += steps + 1 } }
return -1 }
func getNextIndex(j int, length int) int { return (j + 1) % length }
|