1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public class GasStation { public int canCompleteCircuit(int[] gas, int[] cost) { if (gas == null || cost == null || gas.length != cost.length) { return -1; } int total, start, sumRemain; start = total = sumRemain = 0; for (int i = 0; i < gas.length; i++) { int remain = gas[i] - cost[i]; if (sumRemain >= 0) { sumRemain += remain; } else { sumRemain = remain; start = i; } total += remain; } return total >= 0 ? start : -1; } }
|