Problem Link: Connections - Problems - CodeChef
Author: harshit_jain52
If observed carefully, this problem is LCS.
C++ Code
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
int solve(vector<int> &nums1, vector<int> &nums2, int n1, int n2)
{
int dp[n1 + 1][n2 + 1];
for (int i = 0; i <= n1; i++)
dp[i][0] = 0;
for (int j = 0; j <= n2; j++)
dp[0][j] = 0;
for (int i = 1; i <= n1; i++)
{
for (int j = 1; j <= n2; j++)
{
if (nums1[i - 1] == nums2[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[n1][n2];
}
int main()
{
int t;
cin >> t;
while (t--)
{
int x, y;
cin >> x >> y;
vector<int> a(x), b(y);
for (int i = 0; i < x; i++)
{
cin >> a[i];
}
for (int i = 0; i < y; i++)
{
cin >> b[i];
}
cout << solve(a, b, x, y) << endl;
}
}
Time Complexity: O(x*y)