Yes O(n) is possible. Definitely not TSP.
Let xi be the amount of gas available at station i minus the amount of gas required to go to next station.
A requirement is Σ xi ≥ 0 (enough gas to complete a full circle).
Consider Si = x1 + x2 + ... + xi
Note that Sn ≥ 0.
Now pick the smallest (or even largest will do, making it easier to write code for) k such that Sk is the least and start at the station next to it.
Now for k < j ≤ n, we have the gas in tank = Sj - Sk ≥ 0.
for 1 ≤ j ≤ k, we have gas in tank = xk+1 + .. + xn + x1 + x2 + .. + xj = Sn - Sk + Sj ≥ 0.
Thus starting at k+1 will ensure there is enough gas accumulated at each station to get to the next station.
// C++ code. gas[i] is the gas at station i, cost[i] is the cost from station i to (i+1)%n
int circ(vector<int> &gas, vector<int> &cost) {
int min_S=INT_MAX, S=0, position=0;
for(int i=0;i<gas.size();i++)
{
S += gas[i] - cost[i];
if(S<min_S)
{
min_S = S;
position = (i+1) % gas.size();
}
}
if(S>=0)
return position;
else
return -1;
}