|
| 1 | +/** |
| 2 | + * 2002. Maximum Product of the Length of Two Palindromic Subsequences |
| 3 | + * https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a string s, find two disjoint palindromic subsequences of s such that the product of their |
| 7 | + * lengths is maximized. The two subsequences are disjoint if they do not both pick a character at |
| 8 | + * the same index. |
| 9 | + * |
| 10 | + * Return the maximum possible product of the lengths of the two palindromic subsequences. |
| 11 | + * |
| 12 | + * A subsequence is a string that can be derived from another string by deleting some or no |
| 13 | + * characters without changing the order of the remaining characters. A string is palindromic |
| 14 | + * if it reads the same forward and backward. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {string} s |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var maxProduct = function(s) { |
| 22 | + const n = s.length; |
| 23 | + let result = 0; |
| 24 | + |
| 25 | + for (let mask1 = 1; mask1 < (1 << n); mask1++) { |
| 26 | + for (let mask2 = 1; mask2 < (1 << n); mask2++) { |
| 27 | + if (mask1 & mask2) continue; |
| 28 | + const len1 = isPalindrome(s, mask1); |
| 29 | + if (len1 === 0) continue; |
| 30 | + const len2 = isPalindrome(s, mask2); |
| 31 | + if (len2 === 0) continue; |
| 32 | + result = Math.max(result, len1 * len2); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return result; |
| 37 | + |
| 38 | + function isPalindrome(str, mask) { |
| 39 | + const chars = []; |
| 40 | + for (let i = 0; i < n; i++) { |
| 41 | + if (mask & (1 << i)) chars.push(str[i]); |
| 42 | + } |
| 43 | + let left = 0; |
| 44 | + let right = chars.length - 1; |
| 45 | + while (left < right) { |
| 46 | + if (chars[left++] !== chars[right--]) return 0; |
| 47 | + } |
| 48 | + return chars.length; |
| 49 | + } |
| 50 | +}; |
0 commit comments