AlgoMaster Logo

Gas Station

gas=[1, 2, 3, 4, 5],cost=[3, 4, 5, 1, 2]
1public int canCompleteCircuit(int[] gas, int[] cost) {
2    int totalTank = 0;
3    int currentTank = 0;
4    int start = 0;
5
6    for (int i = 0; i < gas.length; i++) {
7        totalTank += gas[i] - cost[i];
8        currentTank += gas[i] - cost[i];
9
10        if (currentTank < 0) {
11            start = i + 1;
12            currentTank = 0;
13        }
14    }
15
16    return totalTank >= 0 ? start : -1;
17}
0 / 15
gas0112233445cost34512