Gas Station

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;
 }
};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s