There was N gas stations along a circular route, where the amount of gas at Station I was gas[i]
.
You had a car with an unlimited gas tank and it costs of gas to travel from station cost[i]
I to its next station (i+ 1). You begin the journey with a 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.
Ideas:
1. Loop through each of the starting points to calculate whether the requirements are met. Time Complexity of O (n^2);
2. Assuming that the remaining amount of petrol is sufficient to travel from the i->j-1, the petrol is not sufficient to travel from J-1 to J, i.e. I cannot travel to J from the start.
At this point, according to the 1th way of thinking, is from I+1 as a new starting point to start the traversal.
But at the first petrol station there must be Gas[i] >= cost[i], the same can not be done from I+1 to J;
and Gas[i]+gas[i+1]-cost[i]-cost[i+1] >= 0, then from I+2 to J can not be completed;
And so on, all points between I and J cannot be fulfilled, and the traversal is started directly from j+1 as a new node.
When I to n satisfies the condition, it is necessary to determine whether the remaining oil amount of I to J is sufficient for 0 to i-1 distance.
The code is as follows:
Public intCancompletecircuit (int[] Gas,int[] cost) { intleft = 0;//Petrol remaining quantityintPass = 0;//gasoline shortage from 0->i-1intStart = 0; for(inti=0; i<gas.length; i++) { left= Gas[i]-Cost[i] +Left ; if(Left < 0) {Pass= left +Pass; Start= i + 1; Left= 0; } } if(pass + left >= 0) returnstart; Else return-1; }
LeetCode-134 gas Station