using System;
public class GFG {
// DP array to store the lengths of longest
// common subsequences with a given sum
static int[, , ] dp = new int[101, 101, 1001];
static int solve(int[] a, int[] b, int n, int m,
int sum)
{
// Initialize the DP array to 0
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
for (int k = 0; k <= sum; k++) {
dp[i, j, k] = 0;
}
}
}
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
for (int k = 0; k <= sum; k++) {
// Base case 1: sum is 0
if (k == 0)
dp[i, j, k] = 0;
// Base case 2: either array is empty
else if (i == 0 || j == 0) {
if (k == 0)
dp[i, j, k] = 0;
else
// Set to a very small negative
// value to indicate
// impossibility
dp[i, j, k] = -1000000000;
}
else if (a[i - 1] == b[j - 1]) {
// Case 1: current elements of both
// arrays are the same Choose or
// don't choose the current element
if (k >= a[i - 1])
dp[i, j, k] = Math.Max(
1
+ dp[i - 1, j - 1,
k - a[i - 1]],
dp[i - 1, j - 1, k]);
else
dp[i, j, k]
= dp[i - 1, j - 1, k];
}
else { // Case 2: current elements of
// both arrays are different
// Choose the longest subsequence
// without the current element
dp[i, j, k]
= Math.Max(dp[i - 1, j, k],
dp[i, j - 1, k]);
}
}
}
}
// Return the final answer, or -1 if it is
// impossible
return (dp[n, m, sum] < 0) ? -1 : dp[n, m, sum];
}
public static void Main()
{
int[] a = { 9, 11, 2, 1, 6, 2, 7 };
int[] b = { 1, 2, 6, 9, 2, 3, 11, 7 };
int n = a.Length;
int m = b.Length;
int sum = 18;
// function call
int ans = solve(a, b, n, m, sum);
Console.WriteLine(
(ans == -1) ? -1
: ans); // Print the answer or -1 if
// it is impossible
}
}