Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

maximum product of word

/* Finding the maximum product of two words Lengths in an array of words. */
//less code but slow
var maxProduct = function (words) {
    let max = 0;
    for (let i = 0; i < words.length; i++) {
        for (let j = i + 1; j < words.length; j++) {
            if (words[i].split("").filter(x => words[j].includes(x)).length === 0) {
                max = Math.max(max, words[i].length * words[j].length);
            }
        }
    }
    return max;
};

//more code but ultra fast
 var maxProduct = function(words) {
    
    const length = words.length;
    const maskes = new Array(length).fill(0);
    for (let i = 0; i < length; i++) {
        const word = words[i];
        const wordLength = word.length;
        for (let j = 0; j < wordLength; j++) {
            maskes[i] |= 1 << (word[j].charCodeAt() - 'a'.charCodeAt());
        }
    }

    
    let max = 0
     for (let i = 0; i < words.length; i++) {
        for (let j = i + 1; j < words.length; j++) {
            if ( (maskes[i] & maskes[j]) === 0 ) {
               max = Math.max(max,words[i].length*words[j].length);
            }
        }

    }
    
    return max
};
 
PREVIOUS NEXT
Tagged: #maximum #product #word
ADD COMMENT
Topic
Name
5+5 =