Skip to content

Commit deda449

Browse files
authored
O(mn)
1 parent 6ec4e71 commit deda449

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
int LCS(string X, string Y, int n, int m) {
6+
int dp[n + 1][m + 1]; // DP - matrix
7+
8+
// initialize 1st row and of dp matrix with 0 according to the base condition of recursion // base case of recursion --> for initialization of dp - matrix
9+
for (int i = 0; i <= n; i++)
10+
for (int j = 0; j <= m; j++)
11+
if (i == 0 || j == 0)
12+
dp[i][j] = 0;
13+
// choise diagram is used to fill rest of the matrix
14+
for (int i = 1; i <= n; i++)
15+
for (int j = 1; j <= m; j++)
16+
if (X[i - 1] == Y[j - 1]) // when last character is same
17+
dp[i][j] = 1 + dp[i - 1][j - 1];
18+
else // when last character is not same -> pick max
19+
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
20+
21+
return dp[n][m]; // last row and last column element will give the length of the LCS;
22+
}
23+
24+
int main() {
25+
string X, Y; cin >> X >> Y;
26+
int n = X.length(), m = Y.length();
27+
28+
cout << LCS(X, Y, n, m) << endl;
29+
return 0;
30+
}
31+
32+
// https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/#:~:text=Time%20complexity%20of%20the%20above,length%20of%20LCS%20is%200.&text=In%20the%20above%20partial%20recursion,%E2%80%9D)%20is%20being%20solved%20twice.

0 commit comments

Comments
 (0)