# [leetcode] 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.

``````class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
for(int startIdx = 0; startIdx < gas.size(); ){
int currentIdx = startIdx;
int gasInTank = 0;
bool isBegin = true;
while(true){
if(currentIdx == startIdx && isBegin != true){
return startIdx;
}
else{
isBegin = false;
gasInTank += gas[currentIdx] - cost[currentIdx];
if(gasInTank < 0){
//if gas is not enough， if we have go over one round, return -1
if(currentIdx < startIdx || currentIdx == gas.size() - 1){
return -1;
}
else{
startIdx = currentIdx + 1;
break;
}
}
else{
currentIdx++;
if(currentIdx == gas.size()){
currentIdx = 0;
}
}
}
}
}
//no suitable station is found
return -1;
}
};
`````` This site uses Akismet to reduce spam. Learn how your comment data is processed.