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.

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 {
 int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {

int N=gas.size();
int try_start=0;
int gas_left=0;
int j=0;
for( j=0;j<N;j++){
if(j==N) {return try_start;}
return try_start<N ? try_start: -1;

Leave a Reply

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

You are commenting using your 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