Two pass solution in JS, but apparently slow compared to others?


  • 0
    J
    var candy = function(ratings) {
        if (!ratings.length) {return 0;}
        if (ratings.length === 1) {return 1;}
        
        var candies = ratings.map(function(d) {return 1;});
    
        var pass = function(d, i) {
            if (i) {
                if (d > ratings[i - 1] && candies[i] <= candies[i - 1]) {
                    candies[i] = candies[i - 1] + 1; 
                }
            }
        };
    
        var passes = 0;
        
        while (passes < 2) {
            ratings.forEach(pass);
            ratings.reverse();
            candies.reverse();
            passes++;
        }
        
        return candies.reduce(function(a, b) {return a + b;})
    };
    

    Who's got a faster one?


Log in to reply
 

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