Monday, December 8, 2014

Gas Station LeetCode

Use two variables to get the index.
diff is checking whether the entire loop has enough gas for the cost.
remain is trying to find the best start location. If it is negative which means we could not start at any previously point. So we count it again from the next point.

public int canCompleteCircuit(int[] gas, int[] cost) {
        int index = -1;
        int diff = 0;
        int remain = 0;
       
        for (int i=0; i<gas.length; i++) {
            diff += gas[i] - cost[i];
            remain += gas[i] - cost[i];
            if (remain < 0) {
                index = i;
                remain = 0;
            }
        }
        return diff >= 0 ? index + 1: -1;
    }

No comments:

Post a Comment