Maximum Product of the Length of Two Palindromic Subsequences Problem
Description
LeetCode Problem 2002.
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.
Return the maximum possible product of the lengths of the two palindromic subsequences.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.
Example 1:

Input: s = "leetcodecom"
Output: 9
Explanation: An optimal solution is to choose "ete" for the 1^st subsequence and "cdc" for the 2^nd subsequence.
The product of their lengths is: 3 * 3 = 9.
Example 2:
Input: s = "bb"
Output: 1
Explanation: An optimal solution is to choose "b" (the first character) for the 1^st subsequence and "b" (the second character) for the 2^nd subsequence.
The product of their lengths is: 1 * 1 = 1.
Example 3:
Input: s = "accbcaxxcxx"
Output: 25
Explanation: An optimal solution is to choose "accca" for the 1^st subsequence and "xxcxx" for the 2^nd subsequence.
The product of their lengths is: 5 * 5 = 25.
Constraints:
2 <= s.length <= 12sconsists of lowercase English letters only.
Solution
Approach: Bitmask Enumeration
The string has at most 12 characters, so every subsequence can be written as an n-bit mask: bit i is set when s[i] is chosen.
First, for each mask decide whether its subsequence is a palindrome, using two pointers that skip unchosen positions, and store the result in p[mask].
The two subsequences must not share a character, so their masks are disjoint. For each palindromic mask i, enumerate the submasks j of its complement ((1 << n) - 1) ^ i with the usual j = (j - 1) & mask loop. Whenever j is also a palindrome, the product of the two popcounts is a candidate. Return the largest one.
Complexity: O(2n * n + 3n) time (each element is in the first mask, the second, or neither) and O(2n) space.
class Solution:
def maxProduct(self, s: str) -> int:
n = len(s)
p = [True] * (1 << n)
for k in range(1, 1 << n):
i, j = 0, n - 1
while i < j:
while i < j and (k >> i & 1) == 0:
i += 1
while i < j and (k >> j & 1) == 0:
j -= 1
if i < j and s[i] != s[j]:
p[k] = False
break
i, j = i + 1, j - 1
ans = 0
for i in range(1, 1 << n):
if p[i]:
mx = ((1 << n) - 1) ^ i
j = mx
a = bin(i).count('1')
while j:
if p[j]:
b = bin(j).count('1')
ans = max(ans, a * b)
j = (j - 1) & mx
return ans