/* Write a function to compute the maximum length palindromic sub-sequence of an array. A palindrome is a sequence which is equal to its reverse. A sub-sequence of an array is a sequence which can be constructed by removing elements of the array. Ex: Given [4,1,2,3,4,5,6,5,4,3,4,4,4,4,4,4,4] should return 10 (all 4's) */ class Interview { public static int maxLengthPalindrome(int[] values) { //ur implementation here }
解法一:
Implemtation is recursive, and it's much worse than O(n^2). Should use recursive with memorization, then can improve to O(n^2).
However, recursive memorization doesn't improve over bottom-up and it has costly overhead. Bottom-up is better in this problem.
public class Solution { public static void main(String[] args) { int arr[] = new int[] {4,1,2,3,4,5,6,5,4,3,4,4,4,4,4,4,4}; System.out.println(maxLengthPalindrome(arr, 0, arr.length-1)); } public static int maxLengthPalindrome(int[] values, int i, int j) { //check if indexes cross each other //return 1 if index overlap for else condition below //return 0 if index i<j for condition if below if(j<=i) return j-i+1; if(values[i]==values[j]) return 2 + maxLengthPalindrome(values, i+1, j-1); else return Math.max(maxLengthPalindrome(values, i+1, j), maxLengthPalindrome(values, i, j-1)); } }
解法二:
The code with the memoization technique which produces O(n^2) complexity is
public int dpLps(int[] a, int i, int j, Integer[][] lps) { if (i > j) return 0; if (lps[i][j] == null) { if (i == j) lps[i][j] = 1; else { if (a[i] == a[j]) lps[i][j] = 2 + dpLps(a, i + 1, j - 1, lps); else lps[i][j] = Math.max(dpLps(a, i + 1, j, lps), dpLps(a, i, j - 1, lps)); } } return lps[i][j]; }
you have to call the function as,
dpLps(a, 0, a.length - 1,new Integer[a.length][a.length])