Maximum Product of the Length of Two Palindromic Subsequences LeetCode solution in C++
1class Solution {2public:3int lca(string &s) {4int n = s.size();5string s1 = s;6string s2 = s;7reverse(s2.begin(), s2.end());8int dp[s.size() + 1][s.size() + 1];9memset(dp, 0, sizeof(dp));10for (int i = 1; i <= n; i++) {11for (int j = 1; j <= n; j++) {12dp[i][j] =13(s1[i - 1] == s2[j - 1]) ? 1 + dp[i - 1][j - 1] : max(dp[i][j - 1], dp[i - 1][j]);14}15}16return dp[n][n];17}18int maxProduct(string s) {19int ans = 0;20int n = s.size();21for (int i = 1; i < (1 << n) - 1; i++) {22string s1 = "", s2 = "";23for (int j = 0; j < n; j++) {24if (i & (1 << j)) {25s1.push_back(s[j]);26} else {27s2.push_back(s[j]);28}29}30ans = max(ans, lca(s1) * lca(s2));31}32return ans;33}34};