Simple Java Solution Easy to Understand O(n)


  • 0
    I
    public int canCompleteCircuit(int[] gas, int[] cost) {
    
        int count = 0;
        int g = 0;
        for (int i = 0; i <  2 * gas.length; i++) {
            g += gas[i % gas.length] - cost[i % gas.length];
            if (g >= 0) {
                count++;
            } else {
                g = 0;
                count = 0;
            }
        }
        return count >= gas.length ? 2 * gas.length - count : -1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.