Skip to content

Commit e781eb5

Browse files
committed
Added Longest Common Subsequence example (dp)
1 parent edb6ef0 commit e781eb5

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

Dynamic_Programming.java

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import java.io.BufferedReader;
22
import java.io.InputStreamReader;
33
import java.io.PrintWriter;
4-
import java.util.Arrays;
54

65
/**
76
*
@@ -31,13 +30,38 @@ public static void main(String[] args) throws Exception {
3130
}
3231

3332
void solve() throws Exception {
34-
longest_increasing_subsequence();
33+
//longest_increasing_subsequence();
34+
longest_common_subsequence();
35+
}
36+
37+
private void longest_common_subsequence() {
38+
String x = "AGGTAB";
39+
String y = "AGTB";
40+
41+
pout.println("LCS: "+lcs(x, y));
42+
}
43+
44+
int lcs(String input1,String input2){
45+
int len1 = input1.length();
46+
int len2 = input2.length();
47+
int dp[][] = new int[len1+1][len2+1];
48+
for(int i=1;i<=len1;i++){
49+
for(int j=1;j<=len2;j++){
50+
if(input1.charAt(i-1)==input2.charAt(j-1)){
51+
dp[i][j] = dp[i-1][j-1] + 1;
52+
}
53+
else
54+
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
55+
}
56+
}
57+
58+
return dp[len1][len2];
3559
}
3660

3761
private void longest_increasing_subsequence() {
3862
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
3963
int n = arr.length;
40-
System.out.println("Length of lis is "
64+
pout.println("Length of lis is "
4165
+ lis(arr, n) + "\n");
4266
}
4367

@@ -61,6 +85,7 @@ int lis(int arr[],int n){
6185

6286
return max;
6387
}
64-
65-
88+
6689
}
90+
91+

0 commit comments

Comments
 (0)