#2002
Maximum Product of the Length of Two Palindromic Subsequences
MediumStringDynamic ProgrammingBacktrackingBit ManipulationBitmaskDynamic ProgrammingBit ManipulationBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n² * 2^n) | O(n^3) |
| Space | O(2^n) | O(n^2) |
💡
Intuition
Time O(n^3)Space O(n^2)
The optimal solution uses dynamic programming to precompute the lengths of the longest palindromic subsequences for all possible pairs of disjoint character sets. This significantly reduces the number of checks needed and allows us to find the maximum product efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Create a function to compute the longest palindromic subsequence for a given string.
- 2Step 2: Use bit manipulation to represent subsets of characters in the string.
- 3Step 3: For each pair of subsets, calculate the product of their palindromic lengths and update the maximum product.
solution.py26 lines
1def longest_palindrome_length(s):
2 n = len(s)
3 dp = [[0] * n for _ in range(n)]
4 for i in range(n):
5 dp[i][i] = 1
6 for length in range(2, n + 1):
7 for i in range(n - length + 1):
8 j = i + length - 1
9 if s[i] == s[j]:
10 dp[i][j] = 2 + (dp[i + 1][j - 1] if length > 2 else 0)
11 else:
12 dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
13 return dp[0][n - 1]
14
15def max_product_palindromic_subsequences(s):
16 n = len(s)
17 max_product = 0
18 for mask1 in range(1 << n):
19 for mask2 in range(mask1 + 1, 1 << n):
20 if mask1 & mask2 == 0:
21 subseq1 = ''.join(s[i] for i in range(n) if mask1 & (1 << i))
22 subseq2 = ''.join(s[i] for i in range(n) if mask2 & (1 << i))
23 len1 = longest_palindrome_length(subseq1)
24 len2 = longest_palindrome_length(subseq2)
25 max_product = max(max_product, len1 * len2)
26 return max_productℹ
Complexity note: The time complexity is reduced to O(n^3) due to the dynamic programming approach for finding palindromic lengths, which is more efficient than checking all pairs of subsequences directly.
- 1Understanding palindromic subsequences is crucial for solving this problem effectively.
- 2Bit manipulation can help efficiently represent and check disjoint subsequences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.