Given two arrays a[] and b[] and an integer K, the task is to find the length of the longest common subsequence such that sum of elements is equal to K.
Examples:
Input: a[] = { 9, 11, 2, 1, 6, 2, 7}, b[] = {1, 2, 6, 9, 2, 3, 11, 7}, K = 18
Output: 3
Explanation: Subsequence { 11, 7 } and { 9, 2, 7 } has sum equal to 18.
Among them { 9, 2, 7 } is longest. Therefore the output will be 3.Input: a[] = { 2, 5, 2, 5, 7, 9, 4, 2}, b[] = { 1, 6, 2, 7, 8 }, K = 8
Output: -1
Approach: The approach to the solution is based on the concept of longest common subsequence and we need to check if sum of elements of subsequence is equal to given value. Follow the steps mentioned below;
- Consider variable sum initialized to given value.
- Each time when elements are included in subsequence, decrease sum value by this element.
- In base condition check if sum value is 0 which implies this subsequence has sum equal to K. Therefore return 0 when sum is zero, else return INT_MIN
Below is the implementation of the above approach :
C++
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std; int solve( int a[], int b[], int i, int j, int sum) { if (sum == 0) return 0; if (sum < 0) return INT_MIN; if (i == 0 || j == 0) { if (sum == 0) return 0; else return INT_MIN; } // If values are same then we can include this // or also can't include this if (a[i - 1] == b[j - 1]) return max( 1 + solve(a, b, i - 1, j - 1, sum - a[i - 1]), solve(a, b, i - 1, j - 1, sum)); return max(solve(a, b, i - 1, j, sum), solve(a, b, i, j - 1, sum)); } // Driver code int main() { int a[] = { 9, 11, 2, 1, 6, 2, 7 }; int b[] = { 1, 2, 6, 9, 2, 3, 11, 7 }; int n = sizeof (a) / sizeof ( int ); int m = sizeof (b) / sizeof ( int ); int sum = 18; int ans = solve(a, b, n, m, sum); if (ans >= 0) cout << ans << endl; else cout << -1; return 0; } |
Java
// Java code to implement the approach import java.io.*; class GFG { static int solve( int a[], int b[], int i, int j, int sum) { if (sum == 0 ) return 0 ; if (sum < 0 ) return Integer.MIN_VALUE; if (i == 0 || j == 0 ) { if (sum == 0 ) return 0 ; else return Integer.MIN_VALUE; } // If values are same then we can include this // or also can't include this if (a[i - 1 ] == b[j - 1 ]) return Math.max( 1 + solve(a, b, i - 1 , j - 1 , sum - a[i - 1 ]), solve(a, b, i - 1 , j - 1 , sum)); return Math.max(solve(a, b, i - 1 , j, sum), solve(a, b, i, j - 1 , sum)); } // Driver code public static void main (String[] args) { 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 ; int ans = solve(a, b, n, m, sum); if (ans >= 0 ) System.out.print(ans); else System.out.print(- 1 ); } } // This code is contributed by hrithikgarg03188. |
Python3
# Python code for the above approach def solve(a, b, i, j, sum ): if sum = = 0 : return 0 if sum < 0 : return - 2147483648 if i = = 0 or j = = 0 : if sum = = 0 : return 0 else : return - 2147483648 # If values are same then we can include this # or also can't include this if (a[i - 1 ] = = b[j - 1 ]): return max ( 1 + solve(a, b, i - 1 , j - 1 , sum - a[i - 1 ]), solve(a, b, i - 1 , j - 1 , sum )) return max (solve(a, b, i - 1 , j, sum ), solve(a, b, i, j - 1 , sum )) # Driver code a = [ 9 , 11 , 2 , 1 , 6 , 2 , 7 ] b = [ 1 , 2 , 6 , 9 , 2 , 3 , 11 , 7 ] n = len (a) m = len (b) sum = 18 ans = solve(a, b, n, m, sum ) if (ans > = 0 ): print (ans) else : print ( - 1 ) # This code is contributed by Potta Lokesh |
C#
// C# code to implement the approach using System; class GFG { static int solve( int [] a, int [] b, int i, int j, int sum) { if (sum == 0) return 0; if (sum < 0) return Int32.MinValue; if (i == 0 || j == 0) { if (sum == 0) return 0; else return Int32.MinValue; } // If values are same then we can include this // or also can't include this if (a[i - 1] == b[j - 1]) return Math.Max(1 + solve(a, b, i - 1, j - 1, sum - a[i - 1]), solve(a, b, i - 1, j - 1, sum)); return Math.Max(solve(a, b, i - 1, j, sum), solve(a, b, i, j - 1, sum)); } // Driver code 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; int ans = solve(a, b, n, m, sum); if (ans >= 0) Console.Write(ans); else Console.Write(-1); } } // This code is contributed by Samim Hossain Mondal.. |
Javascript
<script> // JavaScript code to implement the approach const INT_MIN = -2147483648; const solve = (a, b, i, j, sum) => { if (sum == 0) return 0; if (sum < 0) return INT_MIN; if (i == 0 || j == 0) { if (sum == 0) return 0; else return INT_MIN; } // If values are same then we can include this // or also can't include this if (a[i - 1] == b[j - 1]) return Math.max( 1 + solve(a, b, i - 1, j - 1, sum - a[i - 1]), solve(a, b, i - 1, j - 1, sum)); return Math.max(solve(a, b, i - 1, j, sum), solve(a, b, i, j - 1, sum)); } // Driver code let a = [9, 11, 2, 1, 6, 2, 7]; let b = [1, 2, 6, 9, 2, 3, 11, 7]; let n = a.length; let m = b.length; let sum = 18; let ans = solve(a, b, n, m, sum); if (ans >= 0) document.write(`${ans}`); else document.write( "-1" ); // This code is contributed by rakeshsahani.. </script> |
3
Time Complexity: O(2N ), N max size among both array
Auxiliary Space: O(1)
Efficient approach: An efficient approach is to use memoization to reduce the time complexity where each state stores the maximum length of a subsequence having a sum. Use map to achieve this.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std; // Function to find longest common subsequence having sum // equal to given value int solve( int a[], int b[], int i, int j, int sum, map<string, int >& mp) { if (sum == 0) return 0; if (sum < 0) return INT_MIN; if (i == 0 || j == 0) { if (sum == 0) return 0; else return INT_MIN; } string temp = to_string(i) + '#' + to_string(j) + '#' + to_string(sum); if (mp.find(temp) != mp.end()) return mp[temp]; // If values are same then we can include this // or also can't include this if (a[i - 1] == b[j - 1]) return mp[temp] = max( 1 + solve(a, b, i - 1, j - 1, sum - a[i - 1], mp), solve(a, b, i - 1, j - 1, sum, mp)); return mp[temp] = max(solve(a, b, i - 1, j, sum, mp), solve(a, b, i, j - 1, sum, mp)); } // Driver code int main() { int a[] = { 9, 11, 2, 1, 6, 2, 7 }; int b[] = { 1, 2, 6, 9, 2, 3, 11, 7 }; map<string, int > mp; int n = sizeof (a) / sizeof ( int ); int m = sizeof (b) / sizeof ( int ); int sum = 18; int ans = solve(a, b, n, m, sum, mp); if (ans >= 0) cout << ans << endl; else cout << -1; return 0; } |
Java
// Java code to implement the approach import java.util.*; class GFG{ // Function to find longest common subsequence having sum // equal to given value static int solve( int a[], int b[], int i, int j, int sum, HashMap<String, Integer> mp) { if (sum == 0 ) return 0 ; if (sum < 0 ) return Integer.MIN_VALUE; if (i == 0 || j == 0 ) { if (sum == 0 ) return 0 ; else return Integer.MIN_VALUE; } String temp = String.valueOf(i) + '#' + String.valueOf(j) + '#' + String.valueOf(sum); if (mp.containsKey(temp)) return mp.get(temp); // If values are same then we can include this // or also can't include this if (a[i - 1 ] == b[j - 1 ]) { mp.put(temp, Math.max( 1 + solve(a, b, i - 1 , j - 1 , sum - a[i - 1 ], mp), solve(a, b, i - 1 , j - 1 , sum, mp))); return mp.get(temp); } mp.put(temp, Math.max(solve(a, b, i - 1 , j, sum, mp), solve(a, b, i, j - 1 , sum, mp))); return mp.get(temp); } // Driver code public static void main(String[] args) { int a[] = { 9 , 11 , 2 , 1 , 6 , 2 , 7 }; int b[] = { 1 , 2 , 6 , 9 , 2 , 3 , 11 , 7 }; HashMap<String, Integer> mp = new HashMap<>(); int n = a.length; int m = b.length; int sum = 18 ; int ans = solve(a, b, n, m, sum, mp); if (ans >= 0 ) System.out.print(ans + "\n" ); else System.out.print(- 1 ); } } // This code is contributed by shikhasingrajput |
Python3
# Python code to implement the approach # Function to find longest common subsequence having sum # equal to given value def solve(a, b, i, j, sum , mp): if sum = = 0 : return 0 if sum < 0 : return - 2147483648 if i = = 0 or j = = 0 : if sum = = 0 : return 0 else : return - 2147483648 temp = str (i) + "#" + str (j) + "#" + str ( sum ) if (temp in mp): return mp[temp] # If values are same then we can include this # or also can't include this if (a[i - 1 ] = = b[j - 1 ]): mp[temp] = max ( 1 + solve(a, b, i - 1 , j - 1 , sum - a[i - 1 ], mp),solve(a, b, i - 1 , j - 1 , sum ,mp)) return mp[temp] mp[temp] = max (solve(a, b, i - 1 , j, sum ,mp),solve(a, b, i, j - 1 , sum ,mp)) return mp[temp] # Driver code a = [ 9 , 11 , 2 , 1 , 6 , 2 , 7 ] b = [ 1 , 2 , 6 , 9 , 2 , 3 , 11 , 7 ] n = len (a) m = len (b) sum = 18 mp = {} ans = solve(a, b, n, m, sum , mp) if (ans > = 0 ): print (ans) else : print ( - 1 ) # This code is contributed by Pushpesh Raj |
C#
// C# code to implement the approach using System; using System.Collections.Generic; class GFG { // Function to find longest common subsequence having // sum equal to given value static int solve( int [] a, int [] b, int i, int j, int sum, Dictionary< string , int > mp) { if (sum == 0) return 0; if (sum < 0) return Int32.MinValue; if (i == 0 || j == 0) { if (sum == 0) return 0; else return Int32.MinValue; } string temp = i.ToString() + "#" + j.ToString() + "#" + sum.ToString(); if (mp.ContainsKey(temp)) return mp[temp]; // If values are same then we can include this // or also can't include this if (a[i - 1] == b[j - 1]) return mp[temp] = Math.Max( 1 + solve(a, b, i - 1, j - 1, sum - a[i - 1], mp), solve(a, b, i - 1, j - 1, sum, mp)); return mp[temp] = Math.Max(solve(a, b, i - 1, j, sum, mp), solve(a, b, i, j - 1, sum, mp)); } // Driver code public static void Main() { int [] a = { 9, 11, 2, 1, 6, 2, 7 }; int [] b = { 1, 2, 6, 9, 2, 3, 11, 7 }; Dictionary< string , int > mp = new Dictionary< string , int >(); int n = a.Length; int m = b.Length; int sum = 18; int ans = solve(a, b, n, m, sum, mp); if (ans >= 0) Console.WriteLine(ans); else Console.Write(-1); } } // This code is contributed by Samim Hossain Mondal. |
Javascript
// JavaScript code to implement the approach // Function to find longest common subsequence having sum // equal to given value function solve(a, b, i, j, sum, mp) { if (sum == 0) { return 0; } if (sum < 0) { return -2147483648; } if (i == 0 || j == 0) { if (sum == 0) { return 0; } else { return -2147483648; } } const temp = i + "#" + j + "#" + sum; if (temp in mp) { return mp[temp]; } // If values are same then we can include this // or also can't include this if (a[i - 1] == b[j - 1]) { mp[temp] = Math.max(1 + solve(a, b, i - 1, j - 1, sum - a[i - 1], mp), solve(a, b, i - 1, j - 1, sum, mp)); return mp[temp]; } mp[temp] = Math.max(solve(a, b, i - 1, j, sum, mp), solve(a, b, i, j - 1, sum, mp)); return mp[temp]; } // Driver code const a = [9, 11, 2, 1, 6, 2, 7]; const b = [1, 2, 6, 9, 2, 3, 11, 7]; const n = a.length; const m = b.length; const sum = 18; const mp = {}; const ans = solve(a, b, n, m, sum, mp); if (ans >= 0) { console.log(ans); } else { console.log(-1); } |
3
Time Complexity: O(N*M)
Auxiliary Space: O(N * M)
Another Approach : Using Dp tabulation (Iterative approach)
The approach to solve the problem is same but in this approach we solve the problem without recursion.
Implementation Steps :
- Initialize a 3D DP array dp[n+1][m+1][sum+1] with all values set to 0.
- Iterate over the indices i and j from 0 to n and m, respectively, and the sum k from 0 to sum.
- For each index (i,j,k), check the following cases:
a. If k is 0, set dp[i][j][k] to 0.
b. If either i or j is 0 and k is not 0, set dp[i][j][k] to a very small negative value to indicate impossibility.
c. If the current elements of both arrays a and b are the same, set dp[i][j][k] to the maximum of either including or excluding the current element.
d. If the current elements of both arrays are different, set dp[i][j][k] to the maximum of the longest subsequence without the current element. - The final answer will be stored in dp[n][m][sum]. If the value is negative, the problem is impossible and the answer is -1. Otherwise, return the value of dp[n][m][sum].
below is the implementation of above approach :
C++
// C++ program for above approach #include <bits/stdc++.h> using namespace std; // DP array to store the lengths of longest common subsequences with a given sum int dp[101][101][1001]; int solve( int a[], int b[], int n, int m, int sum) { memset (dp, 0, sizeof (dp)); // 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++) { // 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] = -1e9; } 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 dp[i][j][k] = max(1 + dp[i - 1][j - 1][k - a[i - 1]], 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] = 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]; } // Driver code int main() { int a[] = {9, 11, 2, 1, 6, 2, 7}; int b[] = {1, 2, 6, 9, 2, 3, 11, 7}; int n = sizeof (a) / sizeof ( int ); int m = sizeof (b) / sizeof ( int ); int sum = 18; // function call int ans = solve(a, b, n, m, sum); cout << ((ans == -1) ? -1 : ans) << endl; // Print the answer, or -1 if it is impossible return 0; } // this code is contributed by bhardwajji |
Java
import java.util.Arrays; public class Main { // 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 [][] row : dp) for ( int [] col : row) Arrays.fill(col, 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(String[] args) { 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); System.out.println((ans == - 1 ) ? - 1 : ans); // Print the answer or -1 if it is impossible } } |
Python3
# Python program for above approach # DP array to store the lengths of longest common subsequences with a given sum dp = [[[ 0 for _ in range ( 1001 )] for _ in range ( 101 )] for _ in range ( 101 )] def solve(a, b, n, m, sum ): global dp # Initialize the DP array to 0 for i in range (n + 1 ): for j in range (m + 1 ): for k in range ( sum + 1 ): # Base case 1: sum is 0 if k = = 0 : dp[i][j][k] = 0 # Base case 2: either array is empty elif i = = 0 or 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] = - 1e9 elif a[i - 1 ] = = b[j - 1 ]: # Case 1: current elements of both arrays are the same # Choose or don't choose the current element dp[i][j][k] = max ( 1 + dp[i - 1 ][j - 1 ][k - a[i - 1 ]], 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] = max (dp[i - 1 ][j][k], dp[i][j - 1 ][k]) # Return the final answer, or -1 if it is impossible return - 1 if dp[n][m][ sum ] < 0 else dp[n][m][ sum ] # Driver code if __name__ = = "__main__" : a = [ 9 , 11 , 2 , 1 , 6 , 2 , 7 ] b = [ 1 , 2 , 6 , 9 , 2 , 3 , 11 , 7 ] n = len (a) m = len (b) sum = 18 # function call ans = solve(a, b, n, m, sum ) print (ans if ans ! = - 1 else - 1 ) # Print the answer, or -1 if it is impossible |
C#
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 } } |
Javascript
function solve(a, b, n, m, sum) { // DP array to store the lengths of longest common // subsequences with a given sum const dp = new Array(n + 1) .fill() .map(() => new Array(m + 1) .fill() .map(() => new Array(sum + 1).fill(0)) ); for (let i = 0; i <= n; i++) { for (let j = 0; j <= m; j++) { for (let 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]; } const a = [9, 11, 2, 1, 6, 2, 7]; const b = [1, 2, 6, 9, 2, 3, 11, 7]; const n = a.length; const m = b.length; const sum = 18; // function call const ans = solve(a, b, n, m, sum); console.log(ans === -1 ? -1 : ans); // Print the answer or -1 if it is impossible |
Output:
3
Time Complexity: O(N*M*sum)
Auxiliary Space: O(N*M*sum)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!