JavaScript 2 solutions (Object & Set)


  • 1

    For each kind of candy, we should always distribute to sister first, so we can easily get the answer by counting how many kinds of candy we have and distribute at most half of all candies to her.

    Solution 1: Using object
    var distributeCandies = function(candies) {
        let store = {};
        let kind = 0;
        for (let i in candies) {
            if (!store[candies[i]]) {
                store[candies[i]] = 1;
                kind ++;
            }
        }
    
        return Math.min(candies.length / 2, kind)
    };
    
    Solution 2: Using Set
    
    var distributeCandies = function(candies) {
        return Math.min(new Set(candies).size, candies.length / 2);
    };
    

Log in to reply
 

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