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.
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { // O(n) time complexity // Let xi = gas[i] - cost[i] // 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 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. // e.g., j = k+1, Sj - Sk = (Sk + (gas[k+1]-cost[k+1])) - Sk = gas[k+1] - cost[k+1] > 0 // So we should start at k+1 // for 1 ≤ j ≤ k, we have gas in tank = xk+1 + .. + xn + x1 + x2 + .. + xj = Sn - Sk + Sj = Sn + (Sj-Sk) ≥ 0. // Thus starting at k+1 will ensure there is enough gas accumulated at each station to get to the next station. int minS = Integer.MAX_VALUE, S = 0, position = 0; for (int i = 0; i < gas.length; i++) { S += gas[i] - cost[i]; if (S < minS) { minS = S; position = (i+1) % gas.length; } } if (S >= 0) return position; else return -1; } }
No comments:
Post a Comment