VOOZH about

URL: https://www.geeksforgeeks.org/dsa/length-of-longest-common-subsequence-with-given-sum-k/

⇱ Length of Longest Common Subsequence with given sum K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Length of Longest Common Subsequence with given sum K

Last Updated : 23 Jul, 2025

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 :


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.


Output
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 :

Output:

3

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

Comment