We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Product of the Length of Two Palindromic Subsequences

Difficulty: Medium


Problem Description

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.


Key Insights

  • A palindromic subsequence reads the same forwards and backwards.
  • Disjoint subsequences cannot use the same character from the original string.
  • The problem can be approached using dynamic programming and bit manipulation to find all possible subsequences.
  • The constraints (length of s is at most 12) allow for a combinatorial approach.

Space and Time Complexity

Time Complexity: O(2^n * n^2), where n is the length of the string. This accounts for generating all possible subsequences and checking if they are palindromic. Space Complexity: O(n^2) for storing the lengths of palindromic subsequences.


Solution

To solve the problem, we can utilize dynamic programming to find the longest palindromic subsequence for all possible masks (subsets) of the string. Each mask represents a selection of characters that form a potential subsequence. We will then iterate through all pairs of masks to check if they are disjoint and calculate the product of their lengths.

  1. Generate all possible masks for the string.
  2. For each mask, compute the longest palindromic subsequence.
  3. Compare all pairs of masks, ensuring they are disjoint, and calculate the product of their lengths.
  4. Keep track of the maximum product found.

Code Solutions

def maxProduct(s):
    n = len(s)
    def is_palindrome(subseq):
        return subseq == subseq[::-1]
    
    palin_lengths = []
    
    for mask in range(1 << n):
        subseq = ''.join(s[i] for i in range(n) if mask & (1 << i))
        if is_palindrome(subseq):
            palin_lengths.append(len(subseq))
        else:
            palin_lengths.append(0)
    
    max_product = 0
    for i in range(len(palin_lengths)):
        for j in range(i + 1, len(palin_lengths)):
            if (i & j) == 0:  # Check if masks are disjoint
                max_product = max(max_product, palin_lengths[i] * palin_lengths[j])
    
    return max_product
← Back to All Questions