Skip to content

Commit 97fc11d

Browse files
authored
Update 2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js
1 parent bf53c5c commit 97fc11d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js

+43
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,46 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
const maxProduct = function(s) {
6+
const n = s.length
7+
const limit = (1 << n) - 1
8+
let res = 0
9+
for(let mask = 1; mask < limit; mask++) {
10+
res = Math.max(res, lp(mask) * lp(limit - mask))
11+
}
12+
return res
13+
14+
function lp(state) {
15+
if(state === 0) return 0
16+
const str = []
17+
let idx = 0
18+
// console.log((state))
19+
while(idx < s.length) {
20+
// console.log((state >>> 0).toString(2))
21+
if((state >> idx) & 1) str.push(s[s.length - 1 - idx])
22+
idx++
23+
}
24+
// console.log(str)
25+
const len = str.length
26+
const dp = Array.from({ length: len }, () => Array(len).fill(0))
27+
for(let i = 0; i < len; i++) dp[i][i] = 1
28+
29+
for(let length = 2; length <= len; length++) {
30+
for(let i = 0; i + length - 1 < len; i++) {
31+
const j = i + length - 1
32+
if(str[i] === str[j]) dp[i][j] = dp[i + 1][j - 1] + 2
33+
else dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1])
34+
}
35+
}
36+
37+
// console.log(dp, len)
38+
return dp[0][len - 1]
39+
}
40+
};
41+
42+
// another
43+
144
/**
245
* @param {string} s
346
* @return {number}

0 commit comments

Comments
 (0)