Question:

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&lt;int&gt;&amp; gas, vector&lt;int&gt;&amp; cost) {
int sum = 0;
for(int i = 0; i &lt; gas.size(); ++i)
{
sum = 0;
for(int j = i; j &lt; gas.size(); ++j)
{
sum += gas[j] - cost[j];
if(sum &lt; 0) break;
}
if(sum &amp;lt; 0) continue;
for(int j = 0; j &amp;lt; i; ++j)
{
sum += gas[j] - cost[j];
if(sum &amp;lt; 0) break;
}
if(sum &gt;= 0) return i;
}
return -1;
}
};
*TLE 做法
``````

1. 对于sum(0, n) = diff[0] + diff[1] +…+diff[n], 当且仅当sum >= 0时该题才有解
2.  对于sum(i, j), 当sum(i, j) < 0时，起始出发点不在[i, j-1]中

``````

class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int sum = 0, ptr = 0;
vector<int> diff;
for(int i = 0; i < gas.size(); ++i)
{
diff.push_back(gas[i] - cost[i]);
sum += diff[i];
}
if(sum < 0) return -1;
sum = 0;

while(ptr < diff.size())
{
if(diff[ptr] < 0) { ++ptr; continue; }
sum = 0;
for(int j = ptr; j < diff.size(); ++j)
{
sum += diff[j];
if(sum < 0) { ptr = j; break; }
}
if(sum < 0) continue;
for(int j = 0; j < ptr; ++j)
{
sum += diff[j];
if(sum < 0) { ++ptr; break; }
}
if(sum >= 0) return ptr;
}
return -1;
}
};

``````