Maximum size subset with given sum using Backtracking
Last Updated :
06 Apr, 2023
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++
// C++ Program to implement the
// above approach
#include <bits/stdc++.h>
using namespace std;
// Initialise maximum possible
// length of subsequence
int max_length = 0;
// Store elements to compare
// max_length with its size
// and change the value of
// max_length accordingly
vector<int> store;
// Store the elements of the
// longest subsequence
vector<int> ans;
// Function to find the length
// of longest subsequence
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()) {
// Update max_length
max_length = store.size();
// Store the subsequence
// elements
ans = store;
}
}
for (int i = index + 1;
i < arr.size(); i++) {
if (sum + arr[i] <= k) {
// Recursively proceed
// with obtained sum
find_max_length(arr, i,
sum, k);
// popping elements
// from back
// of vector store
store.pop_back();
}
// if sum > 0 then we don't
// required thatsubsequence
// so return and continue
// with earlier elements
else
return;
}
return;
}
int longestSubsequence(vector<int> arr,
int n, int k)
{
// Sort the given array
sort(arr.begin(), arr.end());
// Traverse the array
for (int i = 0; i < n; i++) {
// If max_length is already
// greater than or equal
// than remaining length
if (max_length >= n - i)
break;
store.clear();
find_max_length(arr, i, 0, k);
}
return max_length;
}
// Driver code
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
// Java Program to implement the
// above approach
import java.util.*;
class GFG{
// Initialise maximum possible
// length of subsequence
static int max_length = 0;
// Store elements to compare
// max_length with its size
// and change the value of
// max_length accordingly
static Vector<Integer> store = new Vector<Integer>();
// Store the elements of the
// longest subsequence
static Vector<Integer> ans = new Vector<Integer>();
// Function to find the length
// of longest subsequence
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())
{
// Update max_length
max_length = store.size();
// Store the subsequence
// elements
ans = store;
}
}
for (int i = index + 1;
i < arr.length; i++)
{
if (sum + arr[i] <= k)
{
// Recursively proceed
// with obtained sum
find_max_length(arr, i,
sum, k);
// popping elements
// from back
// of vector store
store.remove(store.size() - 1);
}
// if sum > 0 then we don't
// required thatsubsequence
// so return and continue
// with earlier elements
else
return;
}
return;
}
static int longestSubsequence(int []arr,
int n, int k)
{
// Sort the given array
Arrays.sort(arr);
// Traverse the array
for (int i = 0; i < n; i++)
{
// If max_length is already
// greater than or equal
// than remaining length
if (max_length >= n - i)
break;
store.clear();
find_max_length(arr, i, 0, k);
}
return max_length;
}
// Driver code
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));
}
}
// This code is contributed by Princi Singh
Python3
# Python3 Program to implement the
# above approach
# Initialise maximum possible
# length of subsequence
max_length = 0
# Store elements to compare
# max_length with its size
# and change the value of
# max_length accordingly
store = []
# Store the elements of the
# longest subsequence
ans = []
# Function to find the length
# of longest subsequence
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)):
# Update max_length
max_length = len(store)
# Store the subsequence
# elements
ans = store
for i in range ( index + 1, len(arr)):
if (sum + arr[i] <= k):
# Recursively proceed
# with obtained sum
find_max_length(arr, i,
sum, k)
# popping elements
# from back
# of vector store
store.pop()
# if sum > 0 then we don't
# required thatsubsequence
# so return and continue
# with earlier elements
else:
return
return
def longestSubsequence(arr, n, k):
# Sort the given array
arr.sort()
# Traverse the array
for i in range (n):
# If max_length is already
# greater than or equal
# than remaining length
if (max_length >= n - i):
break
store.clear()
find_max_length(arr, i, 0, k)
return max_length
# Driver code
if __name__ == "__main__":
arr = [-3, 0, 1, 1, 2]
n = len(arr)
k = 1
print (longestSubsequence(arr, n, k))
# This code is contributed by Chitranayal
C#
// C# program to implement the
// above approach
using System;
using System.Collections.Generic;
class GFG{
// Initialise maximum possible
// length of subsequence
static int max_length = 0;
// Store elements to compare
// max_length with its size
// and change the value of
// max_length accordingly
static List<int> store = new List<int>();
// Store the elements of the
// longest subsequence
static List<int> ans = new List<int>();
// Function to find the length
// of longest subsequence
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)
{
// Update max_length
max_length = store.Count;
// Store the subsequence
// elements
ans = store;
}
}
for(int i = index + 1;
i < arr.Length; i++)
{
if (sum + arr[i] <= k)
{
// Recursively proceed
// with obtained sum
find_max_length(arr, i,
sum, k);
// popping elements
// from back
// of vector store
store.RemoveAt(store.Count - 1);
}
// If sum > 0 then we don't
// required thatsubsequence
// so return and continue
// with earlier elements
else
return;
}
return;
}
static int longestSubsequence(int []arr,
int n, int k)
{
// Sort the given array
Array.Sort(arr);
// Traverse the array
for(int i = 0; i < n; i++)
{
// If max_length is already
// greater than or equal
// than remaining length
if (max_length >= n - i)
break;
store.Clear();
find_max_length(arr, i, 0, k);
}
return max_length;
}
// Driver code
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));
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
// Javascript Program to implement the
// above approach
// Initialise maximum possible
// length of subsequence
let max_length = 0;
// Store elements to compare
// max_length with its size
// and change the value of
// max_length accordingly
let store = [];
// Store the elements of the
// longest subsequence
let ans = [];
// Function to find the length
// of longest subsequence
function find_max_length(arr,index,sum,k)
{
sum = sum + arr[index];
store.push(arr[index]);
if (sum == k)
{
if (max_length < store.length)
{
// Update max_length
max_length = store.length;
// Store the subsequence
// elements
ans = store;
}
}
for (let i = index + 1;
i < arr.length; i++)
{
if (sum + arr[i] <= k)
{
// Recursively proceed
// with obtained sum
find_max_length(arr, i,
sum, k);
// popping elements
// from back
// of vector store
store.pop();
}
// if sum > 0 then we don't
// required thatsubsequence
// so return and continue
// with earlier elements
else
return;
}
return;
}
function longestSubsequence(arr, n, k)
{
// Sort the given array
arr.sort(function(a,b){return a-b;});
// Traverse the array
for (let i = 0; i < n; i++)
{
// If max_length is already
// greater than or equal
// than remaining length
if (max_length >= n - i)
break;
store=[];
find_max_length(arr, i, 0, k);
}
return max_length;
}
// Driver code
let arr = [-3, 0, 1, 1, 2 ];
let n = arr.length;
let k = 1;
document.write(longestSubsequence(arr,n, k));
// This code is contributed by avanitrachhadiya2155
</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.
Similar Reads
Maximum size subset with given sum This is an extended version of the subset sum problem. Here we need to find the size of the maximum size subset whose sum is equal to the given sum. Examples: Input : set[] = {2, 3, 5, 7, 10, 15}, sum = 10 Output : 3 The largest sized subset with sum 10 is {2, 3, 5} Input : set[] = {1, 2, 3, 4, 5} s
8 min read
Find subset with maximum sum under given condition Given values[] and labels[] of n items and a positive integer limit, We need to choose a subset of these items in such a way that the number of the same type of label in the subset should be <= limit and sum of values are maximum among all possible subset choices. Examples: Input: values[] = [5,
6 min read
Subset Sum Problem using Backtracking Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum. Examples:Â Input:Â set[] = {1,2,1}, sum = 3Output:Â [1,2],[2,1]Explanation:Â There are subsets [1,2],[2,1] with sum 3. Input:Â set[] = {3, 34, 4, 12, 5, 2}, sum =
8 min read
Maximum Sum of Array with given MEX Given 3 integers N, K, and X, the task is to construct an array arr[] with the below conditions: Size of the array = NMEX of the array = KAll array elements should be at most XAmong all the array that follows the above condition print the one having the maximum sum of its elements or print -1 if no
7 min read
Find the maximum subset XOR of a given set Given a set of positive integers. find the maximum XOR subset value in the given set. Expected time complexity O(n).Examples:Input: set[] = {2, 4, 5}Output: 7The subset {2, 5} has maximum XOR valueInput: set[] = {9, 8, 5}Output: 13The subset {8, 5} has maximum XOR valueInput: set[] = {8, 1, 2, 12, 7
15+ min read