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 I to its cost[i]
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.
Given gas 4
stations gas[i]=[1,1,3,1]
with, and the cost[i]=[2,2,1,1]
. The starting gas station's index is 2
.
Public classSolution {/** * @paramgas:an array of integers *@paramcost:an array of integers *@return: An integer*/ Public intCancompletecircuit (int[] Gas,int[] cost) { //Write your code here if(Gas = =NULL|| Gas.length = = 0 | | Cost = =NULL|| Cost.length = = 0 | | Gas.length! =cost.length)return-1; intGas_sum = 0; intCost_sum = 0; for(inti = 0; i < gas.length; i++) Gas_sum+=Gas[i]; for(inti = 0; i < cost.length; i++) Cost_sum+=Cost[i]; if(Gas_sum <cost_sum)return-1; intleft = 0; intStart = 0; while(Start <gas.length) { inti =start; for(; i < gas.length; i++) { left+=Gas[i]; Left-=Cost[i]; if(Left < 0) { left= 0; Break; } } if(I! =gas.length) Start= i + 1; Else returnstart; } return-1; }}
Lintcode-medium-gas Station