There are N gas stations along a circular route, where the amount of gas at station I is gas [I].
You have a car with an unlimited gas tank and it costs cost [I] of gas to travel from station I to its next station (I + 1 ). you begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return-1.
Note:
The solution is guaranteed to be unique.
Question:
Regardless of the starting point, the sufficient condition for a circle is that the sum of all gas [I] is greater than or equal to the sum of all cost [I], as long as this condition is met, there must be a point. Starting from this point, you can circle it.
The remaining problem is how to find this point. Starting from the first point, I tried to go forward and used a sum variable to count the remaining amount of fuel in the current mailbox, if the fuel volume at a certain point is negative, it indicates that the route just taken is not feasible. Record the current point as startpoint and start from this point again. If the oil volume reaches a certain point, discard the route you just walked and record the current point as startpoint, start from the current vertex again ...... until the end point is reached, you can determine whether the dog can complete traversal by judging the sum of all gas [I] and cost [I. If not,-1 is returned; otherwise, the latest startpoint is returned (this startpoint is feasible because all other points have been tried and excluded, and stratpoint must exist, so this startpoint must be feasible ).
The Code is as follows:
1 public class Solution { 2 public int canCompleteCircuit(int[] gas, int[] cost) { 3 int startPoint = -1; 4 int currentSum = 0; 5 int total = 0; 6 7 for(int i = 0;i < gas.length;i++){ 8 total += gas[i] - cost[i]; 9 currentSum += gas[i] - cost[i];10 if(currentSum < 0)11 {12 currentSum = 0;13 startPoint = i;14 }15 }16 17 return total >= 0 ? startPoint+1:-1;18 }19 }