# 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.

int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int lenG = gas.size();
int lenC = cost.size();
if(lenG == 0 || lenC == 0 || (lenG != lenC))
{
return -1;
}

int sum = 0;
vector<int> diff;
int tmp = 0;
for(int i = 0; i < lenG; ++i)
{
tmp = gas[i] - cost[i];
diff.push_back(tmp);
sum += tmp;
}

if(sum < 0)
return -1;
int index = 0;
for(int i = 0; i < lenG; ++i)
{
int tmpSum = diff[i];
if(tmpSum < 0)
continue;
int flag = 1;
for(int j = i + 1; j < lenG; ++j)
{
tmpSum += diff[j];
if(tmpSum < 0)
{
flag = 0;
i = j;
break;
}
}

if(flag)
{
index = i;
break;
}
}

return index;
}

11-03 2万

11-12 2171

09-10 6205

07-27 262

08-01 852

02-18 2378

08-14 94

02-20 429

03-27 970

11-06 84