LeetCode 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.

Note:
The solution is guaranteed to be unique.

 

Solution:

Let xi be the amount of gas available at station i minus the amount of gas required to go to next station.

A requirement is Σ xi ≥ 0 (enough gas to complete a full circle).

Consider Si = x1 + x2 + ... + xi

Note that Sn ≥ 0.

Now pick the smallest (or even largest will do, making it easier to write code for) k such that Sk is the least and start at the station next to it.

Now for k < j ≤ n, we have the gas in tank = Sj - Sk ≥ 0.

for 1 ≤ j ≤ k, we have gas in tank = xk+1 + .. + xn + x1 + x2 + .. + xj = Sn - Sk + Sj ≥ 0.

Thus starting at k+1 will ensure there is enough gas accumulated at each station to get to the next station.

 

// gas[i] is the gas at station i, cost[i] is the cost from station i to (i+1)%n
public int canCompleteCircuit(int[] gas, int[] cost) {
    int n = gas.length;
    int minS = Integer.MAX_VALUE, S = 0, pos = 0;
    for(int i=0; i<n; i++) {
        S += gas[i] - cost[i];
        if(S < minS) {
            minS = S;
            pos = (i+1) % n; // i+1==n ? 0 : i+1;
        }
    }
    return S>=0 ? pos : -1;
}

 

你可能感兴趣的:(LeetCode 134 - Gas Station)