![]() |
VOOZH | about |
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;
Below is the implementation of the above approach :
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.
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 :
below is the implementation of above approach :
Output:
3
Time Complexity: O(N*M*sum)
Auxiliary Space: O(N*M*sum)