Skip to content

Commit 6ec4e71

Browse files
authored
O(N * M)
1 parent ccd5fa3 commit 6ec4e71

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
5+
int dp[1001][1001];
6+
7+
int LCS(string X, string Y, int n, int m) {
8+
// base case
9+
if (n == 0 || m == 0)
10+
dp[n][m] = 0;
11+
12+
if (dp[n][m] != -1) // when table is not having -1 then return the value which is preseent in that block
13+
return dp[n][m];
14+
15+
// choice diagram
16+
// when last character is same
17+
if (X[n - 1] == Y[m - 1])
18+
dp[n][m] = 1 + LCS(X, Y, n - 1, m - 1);// count the number and decreament the both's string length // store the value in particular block
19+
// when last character is not same -> pick max
20+
else
21+
dp[n][m] = max(LCS(X, Y, n - 1, m), LCS(X, Y, n, m - 1)); // one take full and another by leaving last char and vice versa // store the value in particular block
22+
23+
return dp[n][m];
24+
}
25+
26+
int main() {
27+
string X, Y; cin >> X >> Y;
28+
int n = X.length(), m = Y.length();
29+
30+
memset(dp, -1, sizeof(dp)); // intialize the whole dp matrix with -1; // from memset we can initialise either -1 and zero;
31+
32+
cout << LCS(X, Y, n, m) << endl;
33+
return 0;
34+
}

0 commit comments

Comments
 (0)