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.
Two problems :
1. The car won't travel anticlockwise.
2. Use i = i + j to speed up the calculation.
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int i, j, len = gas.size(), curgas;
for (i = 0; i <= len - 1; ++i) {
curgas = 0;
for (j = 0; j <= len - 1; ++j) {
curgas += gas[(i + j)%len];
if (curgas >= cost[(i + j)%len])
curgas -= cost[(i + j)%len];
else {
i = i + j;
break;
}
}
if (j >= len)
return i;
/*
curgas = 0;
for (j = 0; j <= len - 1; ++j) {
curgas += gas[(i - j)%len];
if (curgas >= cost[(i - j - 1)%len])
curgas -= cost[(i - j - 1)%len];
else
break;
}
if (j >= len)
return i;
*/
}
return -1;
}
};
A better solution:
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int N = gas.length, startIndex = -1;
int sum = 0, total = 0;
for(int i = 0; i < N; i++){
sum += (gas[i] - cost[i]);
total += (gas[i] - cost[i]);
if(sum < 0){
startIndex = i;
sum = 0;
}
}
return total >= 0 ? startIndex + 1 : -1;
}
}