LeetCode 1771: Maximize Palindrome Length From Subsequences Solution

Master LeetCode problem 1771 (Maximize Palindrome Length From Subsequences), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1771. Maximize Palindrome Length From Subsequences

Problem Explanation

Explanation

To maximize the palindrome length, we need to find the longest palindromic subsequence that can be constructed by concatenating subsequences of word1 and word2. We can approach this problem using dynamic programming.

  1. Initialize a 2D array dp of size n x m, where n is the length of word1 and m is the length of word2.
  2. Traverse through the word1 and word2 characters and fill the dp array based on the following conditions:
    • If the characters match, increment the diagonal cell by 2.
    • Otherwise, take the maximum of the cells above and to the left.
  3. The final answer will be stored in dp[n-1][m-1].

Time Complexity: O(n*m) where n is the length of word1 and m is the length of word2.

Space Complexity: O(n*m) for the dp array.

Solution Code

class Solution {
    public int longestPalindrome(String word1, String word2) {
        int n = word1.length(), m = word2.length();
        int[][] dp = new int[n][m];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (word1.charAt(i) == word2.charAt(j)) {
                    dp[i][j] = (i > 0 && j > 0) ? dp[i-1][j-1] + 2 : 2;
                } else {
                    dp[i][j] = Math.max((i > 0) ? dp[i-1][j] : 0, (j > 0) ? dp[i][j-1] : 0);
                }
            }
        }

        return (dp[n-1][m-1] > 1) ? dp[n-1][m-1] : 0;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1771 (Maximize Palindrome Length From Subsequences)?

This page provides optimized solutions for LeetCode problem 1771 (Maximize Palindrome Length From Subsequences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1771 (Maximize Palindrome Length From Subsequences)?

The time complexity for LeetCode 1771 (Maximize Palindrome Length From Subsequences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1771 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1771 in Java, C++, or Python.

Back to LeetCode Solutions