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.
You can treat two arrays as an array, benifit[i]=gas[i]-cost[i] is the oil that is obtained for each section of the road.
Two principles: 1. If the total benifit is negative, it will not finish in any way.
2. If the oil runs out from a petrol station I, to the section of the gas station J, it will run out of oil at any petrol station between I,j and J or J.
Based on the above two principles, need a variable total statistic benifit, need a subscript start Mark start station, initial 0, need a variable tank record tank. Once the tank is found to be less than 0 at an I point in the process, the start Mark is i+1, which means that the gas station from the previous start to I cannot be used as the starting gas station.
Finally, see if total is less than 0. return-1 If yes, or start.
Code:
1 Public intCancompletecircuit (int[] Gas,int[] cost) {2 intTank = 0;3 intStart = 0;4 intTotal = 0;5 for(inti=0;i<gas.length;i++)6 {7Total + = gas[i]-Cost[i];8Tank + = gas[i]-Cost[i];9 if(tank<0)Ten { OneStart = I+1; ATank=0; - } - } the returnTotal>=0?start:-1; -}
[Leetcode][java] gas station