for Longest Palindromic Subsequence, we either return 2 + findLPSLengthRecursive(st, startIndex+1, endIndex-1); or return Math.max(c1, c2).
The code is below
// case1
return 2 + findLPSLengthRecursive(st, startIndex+1, endIndex-1);
// case 2: skip one element either from the beginning or the end
int c1 = findLPSLengthRecursive(st, startIndex+1, endIndex);
int c2 = findLPSLengthRecursive(st, startIndex, endIndex-1);
return Math.max(c1, c2);
In Longest Palindromic string, can we do the same? I mean either return case 1 or return case2.
letâs say
// case 1
if(st.charAt(startIndex) == st.charAt(endIndex)) {
int remainingLength = endIndex-startIndex-1;
if(remainingLength == findLPSLengthRecursive(st, startIndex+1, endIndex-1))
return remainingLength + 2;
}
// case 2: skip one character either from the beginning or the end
int c2 = findLPSLengthRecursive(st, startIndex+1, endIndex);
int c3 = findLPSLengthRecursive(st, startIndex, endIndex-1);
return Math.max(c2, c3);
if we can do this, then time complexity is O(2^n) which is better than O(3^n)