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.
Input: s = "leetcodecom"Output: 9Explanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence.The product of their lengths is: 3 * 3 = 9.
Input: s = "bb"Output: 1Explanation: An optimal solution is to choose "b" (the first character) for the 1st subsequence and "b" (the second character) for the 2nd subsequence.The product of their lengths is: 1 * 1 = 1.
Input: s = "accbcaxxcxx"Output: 25Explanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence.The product of their lengths is: 5 * 5 = 25.
class Solution: # Time: O(2^n * n + 3^n) with n = len(s) # Space: O(2^n) def max_product(self, s: str) -> int: n = len(s) def is_palindrome(mask: int) -> bool: chars = [s[i] for i in range(n) if mask >> i & 1] return chars == chars[::-1] length = [0] * (1 << n) palindromes: list[int] = [] for mask in range(1, 1 << n): if is_palindrome(mask): length[mask] = mask.bit_count() palindromes.append(mask) best = 0 for a in palindromes: if length[a] * length[a] <= best: continue remaining = ((1 << n) - 1) ^ a # enumerate all submasks of the complement of a sub = remaining while sub: if length[sub]: best = max(best, length[a] * length[sub]) sub = (sub - 1) & remaining return best