Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Question Write a dynamic programming algorithm to fixed the longest palindrome subsequence in a given string.

Solution using Dynamic Programming Let X = a1, a2, ., an be a sequence of n symbols.

Let C[i,j] = maximum length of a palindrome subsequence. If the sequence contains just one element, then C[i,i]=1 since any element will always be a palindrome of its own. We can take this as our basis step. Now, if there is more than one element; There can be two situations, and we can vary our algorithm accordingly. Say we have the following sequence: A1 A2 A3 A4 A5 A6

We can compare A1 and A6 A1 A2 A3 A4 A5 A6

If A1 = A6, Then we know that we have two palindrome elements. We now have to move forward and compare the other elements. We can move to i+1 and j-1, so our to total number of palindromes would be C[i+1,j-1]+2. If A1 A6, Then we have two options to move forward. One, we can keep i static and move to j-1. Two, we can keep j static and move to i+1. Of course, we need the maximum of the two, so our recurrence becomes max{C[i,j-1],C[i+1,j]}. So the entire recurrence of C[i,j] becomes: C[i,j] = { C[i+1,j-1]+2, if ai=aj max{C[i,j-1],C[i+1,j]}, if ai aj } if i < j

We can use memorization here. We can have a table that will store values calculated for each i,j pair. Since we will be starting out from the first and last element with a recursive call for all inner elements, we can store this values in the table and re-use them. The algorithm will run in O(n) time since for each call we will be doing two operations: One, a recursive call upon n elements. Two, an addition or comparison operation which will take constant time.

You might also like