My javascript code, beat 96%


  • 0
    D
    /**
     * @param {number[]} gas
     * @param {number[]} cost
     * @return {number}
     */
    var canCompleteCircuit = function(gas, cost) {
    
        for(var i = 0;i<gas.length;i++){
            var res = canComplete(gas,cost,i);
            if(res[1]){
                return i;
            }
            i = res[0];
        }
        return -1;
    };
    
    
    var canComplete = function(gas,cost,idx){
        var curr = 0;
        for(var i = 0;i<gas.length;i++){
            curr = curr + gas[(idx + i)% gas.length] - cost[(idx + i)% cost.length];
            if(curr<0){
                return [idx+i,false];
            }
        }
        return [0,true];
    };
    

Log in to reply
 

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