This is one of the popular problem being asked in interviews.

Problem : There are N cng gas stations along a circular route, where the amount of gas at each station i is cgas[i].

You have a vehicle with an unlimited gas tank and it costs amount[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 minimum starting gas station’s index if you can travel around the route once else return -1.

Completing route means starting at i and again ending up at i again.

Consider example:

cgas = { 2,4,6}, cost ={1,3,6}



If cgas[0]>cost[0] means it has enough gas to travel to next station as the cost is 1 and the remaining gas =1 (2-1).



At cgas[1] we have (1+4) gas and cost[1] = 3 which makes the remaining gas as 2. At cgas[2] we have total gas as 8(6+2) while cost[2]=6. So it has enough gas(8-6 =2) to travel back to index 0.

Below is the Code implementation :

int CompleteRoute(const vector &cgas, const vector &cost) { /* total_gas = sum of gas at each station total_cost = sum of cost of gas at each station index = starting_index gas_remaining = gas remained at each station */ int total_gas=0,total_cost=0,index=0,gas_remaining=0; for(auto i = 0;i<cgas.size();i++) { total_gas += cgas[i]; // total_cost += cost[i]; gas_remaining += cgas[i] - cost[i]; if(gas_remaining < 0) { gas_remaining=0; index=i+1; } } if (total_gas < total_cost) return -1 else return index; }

If you have any feedback or suggestion . Please leave a comment.