|
| 1 | +// Java code to implement the approach |
| 2 | +import java.io.*; |
| 3 | +class answer { |
| 4 | + |
| 5 | +static int solve(int a[], int b[], int i, int j, int sum) |
| 6 | +{ |
| 7 | + if (sum == 0) |
| 8 | + return 0; |
| 9 | + if (sum < 0) |
| 10 | + return Integer.MIN_VALUE; |
| 11 | + |
| 12 | + if (i == 0 || j == 0) { |
| 13 | + if (sum == 0) |
| 14 | + return 0; |
| 15 | + else |
| 16 | + return Integer.MIN_VALUE; |
| 17 | + } |
| 18 | + |
| 19 | + // If values are same then we can include this |
| 20 | + // or also can't include this |
| 21 | + if (a[i - 1] == b[j - 1]) |
| 22 | + return Math.max( |
| 23 | + 1 + solve(a, b, i - 1, j - 1, sum - a[i - 1]), |
| 24 | + solve(a, b, i - 1, j - 1, sum)); |
| 25 | + |
| 26 | + return Math.max(solve(a, b, i - 1, j, sum), |
| 27 | + solve(a, b, i, j - 1, sum)); |
| 28 | +} |
| 29 | + |
| 30 | +// Driver code |
| 31 | +public static void main (String[] args) { |
| 32 | + int a[] = { 9, 11, 2, 1, 6, 2, 7 }; |
| 33 | + int b[] = { 1, 2, 6, 9, 2, 3, 11, 7 }; |
| 34 | + int n = a.length; |
| 35 | + int m = b.length; |
| 36 | + int sum = 18; |
| 37 | + |
| 38 | + int ans = solve(a, b, n, m, sum); |
| 39 | + if (ans >= 0) |
| 40 | + System.out.print(ans); |
| 41 | + else |
| 42 | + System.out.print(-1); |
| 43 | +} |
| 44 | +} |
| 45 | + |
| 46 | + |
0 commit comments