Gas Station
A brute force solution to this problem is that we try to start at every position and test if we can finish the whole travel. But there is obviously a better linear solution. At first we have the following observations:
- If we start at
iand after traveled tojwe find we can not move forward any more, then we can not start at either. Thus we should try next from instead of . - If we can start at
iand travel back in a circuit, we must be able to travel fromithe end of array. - If we find the first position one can travel to the end of array at
iand gas left ispsum, we can then travel back toi - 1from the start of array if and only ifpsum >= (psum - sum), wheresumis the total gas remain after visited every station andpsum - sumstands for gas needed to travel throught from0toi - 1.psum - summust be a positive number. - We find that
psum >= psum - sumis equivalent tosum >= 0. That is, if the total gas remain after visited every station, we can always travels back, so the problem becames find the firstithat can let you travels to the end of array.
Code based on this solution:
public class GasStation {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
int total = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if (sum < 0) {
sum = 0;
start = i + 1;
}
}
if (total >= 0) return start;
return -1;
}
}