1771. Maximize Palindrome Length From Subsequences
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.
- Initialize a 2D array
dp
of sizen x m
, wheren
is the length ofword1
andm
is the length ofword2
. - Traverse through the
word1
andword2
characters and fill thedp
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.
- 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.
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.