We have discussed Overlapping Subproblems and Optimal Substructure properties in Set 1 and Set 2respectively. We also discussed one example problem in Set 3. Let us discuss Longest Common Subsequence (LCS) problem as one more example problem that can be solved using Dynamic Programming.

LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of length n has 2^n different possible subsequences.

It is a classic computer science problem, the basis of diff (a file comparison program that outputs the differences between two files), and has applications in bioinformatics.

Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.

Java Code:-

import java.util.*;
class test{
public static void main(String[] args){
String s1="AGGTAB";
String s2="GXTXAYB";
System.out.println(LCS(s1,s2));
}
public static int LCS(String A, String B) {
if (A.length() == 0 || B.length() == 0) {
return 0;
}
int lenA = A.length();
int lenB = B.length();
if (A.charAt(lenA - 1) == B.charAt(lenB - 1)) {
return 1 + LCS(A.substring(0, lenA - 1), B.substring(0, lenB - 1));
} else {
return Math.max(
LCS(A.substring(0, lenA - 1), B.substring(0, lenB)),
LCS(A.substring(0, lenA), B.substring(0, lenB - 1)));
}
}
}