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 codeint 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 approachimport 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 approachdef 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 codea = [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 approachusing 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 valueint 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 codeint 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 approachimport 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 valuedef 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 codea = [9, 11, 2, 1, 6, 2, 7]b = [1, 2, 6, 9, 2, 3, 11, 7]n = len(a)m = len(b)sum = 18mp = {}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 approachusing 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 valuefunction 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 thisif (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 codeconst 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 sumint 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 codeint 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 sumdp = [[[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 codeif __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 callconst 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!
