Skip to content
Related Articles

Related Articles

Length of Longest Common Subsequence with given sum K

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 24 May, 2022

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>

 
 

Output

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.

 
 

Output

3

 

Time Complexity: O(N*M) 
Auxiliary Space: O(N * M)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!