Getting the duration of the longest palindrome subsequence

This solution works, but I'm not sure if it can be improved. Does anyone have any ideas?

class Ideone
{
    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) {
        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));      
    }
}
+4
source share
1 answer

The problem with your approach is that this will lead to multiple repetitions for the same subarrays. Consider this sequence:

1 2 3 4 5

You will make recursive calls for these two subarrays:

2 3 4 5
1 2 3 4

which, in turn, includes recursive calls for them:

3 4 5
2 3 4
2 3 4      // duplicate!
1 2 3

which, in turn, includes:

4 5
3 4
3 4        // duplicate!
2 3
3 4        // duplicate!
2 3        // duplicate!
2 3        // duplicate!
1 2

., . , O (2 n), , O (n 2).

( " " ): n & times; n . "bottom" — 1, 2 .. , . n, , , - .

, (, m) ( m & min; 1 m +, 2), , n, n & times; n; , n & times; n ( , , ).

+2

All Articles