Maximum Product of the Length of Two Palindromic Subsequences LeetCode solution in JavaScript

1
/**
2
* @param {string} s
3
* @return {number}
4
*/
5
var maxProduct = function (s) {
6
const n = s.length;
7
let map = new Map();
8
let res = 0;
9

10
for (let mask = 1; mask < 2 ** n; mask++) {
11
let str = "";
12
for (let i = 0; i < n; i++) {
13
if (mask & (1 << i)) {
14
str += s.charAt(n - 1 - i);
15
}
16
}
17
if (isPalindrom(str)) {
18
let length = str.length;
19
map.set(mask, length);
20
}
21
}
22

23
map.forEach((l1, m1) => {
24
map.forEach((l2, m2) => {
25
if ((m1 & m2) == 0) {
26
res = Math.max(res, l1 * l2);
27
}
28
});
29
});
30

31
return res;
32
};
33

34
function isPalindrom(str) {
35
let l = 0;
36
let r = str.length - 1;
37

38
while (l < r) {
39
if (str.charAt(l) != str.charAt(r)) {
40
return false;
41
}
42
l++;
43
r--;
44
}
45

46
return true;
47
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0