Produk maksimum dari panjang kata leetcode solusi
/* 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
};
ofroog