Maximum size subset with given sum using Backtracking
Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subsequence with a sum equal to K.
Examples:
Input: arr[] = {-4, -2, -2, -1, 6}, K = 0
Output: 3
Explanation:
The longest subsequence is of length 3 which is {-4, -2, 6} having sum 0.
Input: arr[] = {-3, 0, 1, 1, 2}, K = 1
Output: 5
Explanation: The longest subsequence is of length 5 which is {-3, 0, 1, 1, 2} having sum 1.
Naive Approach: The simplest approach to solve the problem is to generate all the possible subsequences of different lengths and check if their sum is equal to K. Out of all these subsequences with sum K, find the subsequence with the longest length.
Time complexity: O(2N)
Recursive & Backtracking Approach: The basic approach of this problem is to sort the vector and find the sum of all the possible subsequences and pick up the subsequence with the maximum length having the given sum. This can be done using Recursion and Backtracking.
Follow the steps below to solve this problem:
- Sort the given array/vector.
- Initialize a global variable max_length to 0, which stores the maximum length subset.
- For every index i in the array, call the recursion function to find out all the possible subsets with elements in the range [i, N-1] having sum K.
- Every time a subset with sum K is found, check if its size is greater than the current max_length value. If yes, then update the value of max_length.
- After all the possible subset sums are computed, return the max_length.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int max_length = 0;
vector< int > store;
vector< int > ans;
void find_max_length(
vector< int >& arr,
int index, int sum, int k)
{
sum = sum + arr[index];
store.push_back(arr[index]);
if (sum == k) {
if (max_length < store.size()) {
max_length = store.size();
ans = store;
}
}
for ( int i = index + 1;
i < arr.size(); i++) {
if (sum + arr[i] <= k) {
find_max_length(arr, i,
sum, k);
store.pop_back();
}
else
return ;
}
return ;
}
int longestSubsequence(vector< int > arr,
int n, int k)
{
sort(arr.begin(), arr.end());
for ( int i = 0; i < n; i++) {
if (max_length >= n - i)
break ;
store.clear();
find_max_length(arr, i, 0, k);
}
return max_length;
}
int main()
{
vector< int > arr{ -3, 0, 1, 1, 2 };
int n = arr.size();
int k = 1;
cout << longestSubsequence(arr,
n, k);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int max_length = 0 ;
static Vector<Integer> store = new Vector<Integer>();
static Vector<Integer> ans = new Vector<Integer>();
static void find_max_length(
int []arr,
int index, int sum, int k)
{
sum = sum + arr[index];
store.add(arr[index]);
if (sum == k)
{
if (max_length < store.size())
{
max_length = store.size();
ans = store;
}
}
for ( int i = index + 1 ;
i < arr.length; i++)
{
if (sum + arr[i] <= k)
{
find_max_length(arr, i,
sum, k);
store.remove(store.size() - 1 );
}
else
return ;
}
return ;
}
static int longestSubsequence( int []arr,
int n, int k)
{
Arrays.sort(arr);
for ( int i = 0 ; i < n; i++)
{
if (max_length >= n - i)
break ;
store.clear();
find_max_length(arr, i, 0 , k);
}
return max_length;
}
public static void main(String[] args)
{
int []arr = { - 3 , 0 , 1 , 1 , 2 };
int n = arr.length;
int k = 1 ;
System.out.print(longestSubsequence(arr,
n, k));
}
}
|
Python3
max_length = 0
store = []
ans = []
def find_max_length(arr, index, sum , k):
global max_length
sum = sum + arr[index]
store.append(arr[index])
if ( sum = = k):
if (max_length < len (store)):
max_length = len (store)
ans = store
for i in range ( index + 1 , len (arr)):
if ( sum + arr[i] < = k):
find_max_length(arr, i,
sum , k)
store.pop()
else :
return
return
def longestSubsequence(arr, n, k):
arr.sort()
for i in range (n):
if (max_length > = n - i):
break
store.clear()
find_max_length(arr, i, 0 , k)
return max_length
if __name__ = = "__main__" :
arr = [ - 3 , 0 , 1 , 1 , 2 ]
n = len (arr)
k = 1
print (longestSubsequence(arr, n, k))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int max_length = 0;
static List< int > store = new List< int >();
static List< int > ans = new List< int >();
static void find_max_length( int []arr,
int index,
int sum, int k)
{
sum = sum + arr[index];
store.Add(arr[index]);
if (sum == k)
{
if (max_length < store.Count)
{
max_length = store.Count;
ans = store;
}
}
for ( int i = index + 1;
i < arr.Length; i++)
{
if (sum + arr[i] <= k)
{
find_max_length(arr, i,
sum, k);
store.RemoveAt(store.Count - 1);
}
else
return ;
}
return ;
}
static int longestSubsequence( int []arr,
int n, int k)
{
Array.Sort(arr);
for ( int i = 0; i < n; i++)
{
if (max_length >= n - i)
break ;
store.Clear();
find_max_length(arr, i, 0, k);
}
return max_length;
}
public static void Main(String[] args)
{
int []arr = { -3, 0, 1, 1, 2 };
int n = arr.Length;
int k = 1;
Console.Write(longestSubsequence(arr,
n, k));
}
}
|
Javascript
<script>
let max_length = 0;
let store = [];
let ans = [];
function find_max_length(arr,index,sum,k)
{
sum = sum + arr[index];
store.push(arr[index]);
if (sum == k)
{
if (max_length < store.length)
{
max_length = store.length;
ans = store;
}
}
for (let i = index + 1;
i < arr.length; i++)
{
if (sum + arr[i] <= k)
{
find_max_length(arr, i,
sum, k);
store.pop();
}
else
return ;
}
return ;
}
function longestSubsequence(arr, n, k)
{
arr.sort( function (a,b){ return a-b;});
for (let i = 0; i < n; i++)
{
if (max_length >= n - i)
break ;
store=[];
find_max_length(arr, i, 0, k);
}
return max_length;
}
let arr = [-3, 0, 1, 1, 2 ];
let n = arr.length;
let k = 1;
document.write(longestSubsequence(arr,n, k));
</script>
|
Time Complexity: O(N3)
Auxiliary Space: O(N)
Dynamic Programming Approach: Refer to this article for a further optimized approach to solve the problem.
Last Updated :
06 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...