Problem Link
https://leetcode.com/problems/gas-station/
Detailed Step-by-Step Explanation
https://leetcode.com/problems/gas-station/solutions/7439501/most-optimal-approach-explanation-with-d-es79

Solution
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalGas = 0;
int totalCost = 0;
for(int i=0; i<gas.length; i++) {
totalGas += gas[i];
totalCost += cost[i];
}
if(totalGas < totalCost) {
return -1;
}
int currGas = 0;
int startIndex = 0;
for(int i=0; i<gas.length; i++) {
currGas += gas[i] - cost[i];
if(currGas < 0) {
startIndex = i + 1;
currGas = 0;
}
}
return startIndex;
}
}
Top comments (0)