134. Gas Station
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.
Two problems for this :
- if sum(gas) - sum(cost) >= 0, then there is a point you can start and complete.
- if at certain point k, if sum(gas[0..k]) - sum(cost[0..k]) <0 then k is not possible to begin with, then reset the current sum to 0 , k + 1 will be the result.
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int station = -1;
int current =0;
int tank = 0;
for(int i=0; i< gas.length; i++){
tank += gas[i] - cost[i];
current += gas[i] - cost[i];
if(current < 0){
current = 0;
station = i;
}
}
if (tank < 0) return -1;
return station+1;
}
}