Here's my code:
public int canCompleteCircuit(int[] gas, int[] cost) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int tank = 0;
int counter = 0;
int curIndex = 0;
int ret = 0;
boolean reset = true;
while(tank >= 0 && counter < gas.length){
if(reset){
if(gas[curIndex]cost[curIndex]>=0){
tank += gas[curIndex]cost[curIndex];
counter++;
ret = curIndex;
reset = false;
}
else if(curIndex == gas.length1) return 1;
curIndex++;
}
else{
tank+=gas[curIndex]cost[curIndex];
if(tank < 0){
if(ret == gas.length1) return 1;
tank = 0;
counter = 0;
ret = curIndex;
reset = true;
}
else{
counter++;
curIndex++;
}
}
if(curIndex == gas.length) curIndex = 0;
}
return ret;
}
The idea is if we start at any ith station, where ith station has positive gascost,and we fail at kth station(total gas < 0), starting from any station between ith and kth will not be possible. Thus, when we fail at k, next time we try to start at a station after k, where the station has positive gascost, and see if we can finish the circuit from there. If at the end of the gas/cost array the gas  cost value is still negative or starting at the end of the array is still not a valid solution, we return 1;
In this way we can reduce the run time to linear time. Is there a better solution?
I think the following two things might need some clarification in the problem:

Since the gas stations are on a circle, can we travel backward? I did not count the case when traveling to the left direction of the array works but traveling to the right does not work. In my understanding, at ith station, the cost to travel to the right will be cost[i] but the cost to travel to the left will be cost[i1].

How do we define "complete the circuit"? It seems that the circuit is regarded as completed if we can start at ith station and arrive at ith station eventually, not just i1th station. Initially I had this line:
if(gas.length == 1) return 0;
but it failed the test case "[4], [5]".