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.

My solution: Started with a brutal force solution, then optimized it to the following linear solution. Finally got it right! ðŸ˜€

class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int N=gas.size();
int try_start=0;
do{
int gas_left=0;
int j=0;
for( j=0;j<N;j++){
Â Â Â gas_left+=gas[(try_start+j)%N]-cost[(try_start+j)%N];
Â Â Â if(gas_left<0){
Â Â Â Â Â Â Â try_start+=j+1;
Â Â Â Â Â Â Â break;
Â Â Â }
}
//cout<<j<<endl;
if(j==N) {return try_start;}
}while(try_start<N);
return try_start<N ? try_start: -1;
}
};

### Like this:

Like Loading...

*Related*