Count ways to split array into pair of subsets with difference between their sum equal to K
Last Updated :
12 Apr, 2023
Given an array arr[] consisting of N integers and an integer K, the task is to find the number of ways to split the array into a pair of subsets such that the difference between their sum is K.
Examples:
Input: arr[] = {1, 1, 2, 3}, K = 1
Output: 3
Explanation:
Following splits into a pair of subsets satisfies the given condition:
- {1, 1, 2}, {3}, difference = (1 + 1 + 2) – 3 = 4 – 3 = 1.
- {1, 3} {1, 2}, difference = (1 + 3) – (1 + 2) = 4 – 3 = 1.
- {1, 3} {1, 2}, difference = (1 + 3) – (1 + 2) = 4 – 3 = 1.
Therefore, the count of ways to split is 3.
Input: arr[] = {1, 2, 3}, K = 2
Output: 1
Explanation:
The only possible split into a pair of subsets satisfying the given condition is {1, 3}, {2}, where the difference = (1 + 3) – 2 = 4 – 2 =2.
Therefore, the count of ways to split is 1.
Naive Approach: The simple approach to solve the given problem is to generate all the possible subsets and store the sum of each subset in an array say subset[]. Then, check if there exist any pair exists in the array subset[] whose difference is K. After checking for all the pairs, print the total count of such pairs as the result.
Time Complexity: O(2N)
Auxiliary Space: O(2N)
Efficient Approach: The above approach can be optimized using the following observations.
Let the sum of the first and second subsets be S1 and S2 respectively, and the sum of array elements be Y.
Now, the sum of both the subsets must be equal to the sum of the array elements.
Therefore, S1 + S2 = Y — (1)
To satisfy the given condition, their difference must be equal to K.
Therefore, S1 – S2 = K — (2)
Adding (1) & (2), the equation obtained is
S1 = (K + Y)/2 — (3)
Therefore, for a pair of subsets having sums S1 and S2, equation (3) must hold true, i.e., the sum of elements of the subset must be equal to (K + Y)/2. Now, the problem reduces to counting the number of subsets with a given sum. This problem can be solved using Dynamic Programming, whose recurrence relation is as follows:
dp[i][C] = dp[i + 1][C – arr[i]] + dp[i + 1][C]
Here, dp[i][C] stores the number of subsets of the subarray arr[i … N – 1], such that their sum is equal to C.
Thus, the recurrence is very trivial as there are only two choices i.e., either consider the ith array element in the subset or don’t.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
#define maxN 20
#define maxSum 50
#define minSum 50
#define base 50
int dp[maxN][maxSum + minSum];
bool v[maxN][maxSum + minSum];
int findCnt( int * arr, int i,
int required_sum,
int n)
{
if (i == n) {
if (required_sum == 0)
return 1;
else
return 0;
}
if (v[i][required_sum + base])
return dp[i][required_sum + base];
v[i][required_sum + base] = 1;
dp[i][required_sum + base]
= findCnt(arr, i + 1,
required_sum, n)
+ findCnt(arr, i + 1,
required_sum - arr[i], n);
return dp[i][required_sum + base];
}
void countSubsets( int * arr, int K,
int n)
{
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += arr[i];
}
int S1 = (sum + K) / 2;
cout << findCnt(arr, 0, S1, n);
}
int main()
{
int arr[] = { 1, 1, 2, 3 };
int N = sizeof (arr) / sizeof ( int );
int K = 1;
countSubsets(arr, K, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static int maxN = 20 ;
static int maxSum = 50 ;
static int minSum = 50 ;
static int Base = 50 ;
static int [][] dp = new int [maxN][maxSum + minSum];
static boolean [][] v = new boolean [maxN][maxSum + minSum];
static int findCnt( int [] arr, int i,
int required_sum,
int n)
{
if (i == n) {
if (required_sum == 0 )
return 1 ;
else
return 0 ;
}
if (v[i][required_sum + Base])
return dp[i][required_sum + Base];
v[i][required_sum + Base] = true ;
dp[i][required_sum + Base]
= findCnt(arr, i + 1 ,
required_sum, n)
+ findCnt(arr, i + 1 ,
required_sum - arr[i], n);
return dp[i][required_sum + Base];
}
static void countSubsets( int [] arr, int K,
int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
{
sum += arr[i];
}
int S1 = (sum + K) / 2 ;
System.out.print(findCnt(arr, 0 , S1, n));
}
public static void main(String[] args)
{
int [] arr = { 1 , 1 , 2 , 3 };
int N = arr.length;
int K = 1 ;
countSubsets(arr, K, N);
}
}
|
Python3
maxN = 20 ;
maxSum = 50 ;
minSum = 50 ;
Base = 50 ;
dp = [[ 0 for i in range (maxSum + minSum)] for j in range (maxN)];
v = [[ False for i in range (maxSum + minSum)] for j in range (maxN)];
def findCnt(arr, i, required_sum, n):
if (i = = n):
if (required_sum = = 0 ):
return 1 ;
else :
return 0 ;
if (v[i][required_sum + Base]):
return dp[i][required_sum + Base];
v[i][required_sum + Base] = True ;
dp[i][required_sum + Base] = findCnt(arr, i + 1 , required_sum, n)\
+ findCnt(arr, i + 1 , required_sum - arr[i], n);
return dp[i][required_sum + Base];
def countSubsets(arr, K, n):
sum = 0 ;
for i in range (n):
sum + = arr[i];
S1 = ( sum + K) / / 2 ;
print (findCnt(arr, 0 , S1, n));
if __name__ = = '__main__' :
arr = [ 1 , 1 , 2 , 3 ];
N = len (arr);
K = 1 ;
countSubsets(arr, K, N);
|
C#
using System;
class GFG {
static int maxN = 20;
static int maxSum = 50;
static int minSum = 50;
static int Base = 50;
static int [,] dp = new int [maxN, maxSum + minSum];
static bool [,] v = new bool [maxN, maxSum + minSum];
static int findCnt( int [] arr, int i,
int required_sum,
int n)
{
if (i == n) {
if (required_sum == 0)
return 1;
else
return 0;
}
if (v[i, required_sum + Base])
return dp[i, required_sum + Base];
v[i,required_sum + Base] = true ;
dp[i,required_sum + Base]
= findCnt(arr, i + 1,
required_sum, n)
+ findCnt(arr, i + 1,
required_sum - arr[i], n);
return dp[i,required_sum + Base];
}
static void countSubsets( int [] arr, int K,
int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
{
sum += arr[i];
}
int S1 = (sum + K) / 2;
Console.Write(findCnt(arr, 0, S1, n));
}
static void Main()
{
int [] arr = { 1, 1, 2, 3 };
int N = arr.Length;
int K = 1;
countSubsets(arr, K, N);
}
}
|
Javascript
<script>
var maxN = 20;
var maxSum = 50;
var minSum = 50;
var base = 50;
var dp = Array.from(Array(maxN),()=> Array(maxSum+minSum));
var v = Array.from(Array(maxN), ()=> Array(maxSum+minSum));
function findCnt(arr, i, required_sum, n)
{
if (i == n) {
if (required_sum == 0)
return 1;
else
return 0;
}
if (v[i][required_sum + base])
return dp[i][required_sum + base];
v[i][required_sum + base] = 1;
dp[i][required_sum + base]
= findCnt(arr, i + 1,
required_sum, n)
+ findCnt(arr, i + 1,
required_sum - arr[i], n);
return dp[i][required_sum + base];
}
function countSubsets(arr, K, n)
{
var sum = 0;
for ( var i = 0; i < n; i++) {
sum += arr[i];
}
var S1 = (sum + K) / 2;
document.write( findCnt(arr, 0, S1, n));
}
var arr = [ 1, 1, 2, 3 ];
var N = arr.length;
var K = 1;
countSubsets(arr, K, N);
</script>
|
Time Complexity: O(N*K)
Auxiliary Space: O(N*K)
Efficient approach : Using DP Tabulation method ( Iterative approach )
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls.
Steps to solve this problem :
- Calculate the total sum of elements in the given array.
- Calculate the value of S1 using the formula (sum + K) / 2, where K is the given difference.
- Create a 2D dp array of size (n+1)x(S1+1), where n is the size of the given array.
- Initialize the base case of dp[i][0] as 1 for all i from 0 to n.
- Fill the dp array using the choice diagram approach. For each element in the array, we have two choices: include it or exclude it. If we include it, we reduce the sum by the value of that element, and if we exclude it, we leave the sum as it is. So, we update the dp array accordingly.
- Return the value of dp[n][S1], which represents the count of subsets with the required sum S1.
Implementation :
C++
#include <bits/stdc++.h>
using namespace std;
int countSubsets( int * arr, int K, int n) {
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
int S1 = (sum + K) / 2;
vector<vector< int >> dp(n+1, vector< int >(S1+1, 0));
for ( int i = 0; i <= n; i++)
dp[i][0] = 1;
for ( int i = 1; i <= n; i++) {
for ( int j = 0; j <= S1; j++) {
if (arr[i-1] <= j) {
dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]];
}
else {
dp[i][j] = dp[i-1][j];
}
}
}
return dp[n][S1];
}
int main() {
int arr[] = {1, 1, 2, 3};
int N = sizeof (arr) / sizeof ( int );
int K = 1;
cout << countSubsets(arr, K, N) << endl;
return 0;
}
|
Java
import java.util.*;
class Main
{
static int countSubsets( int [] arr, int K, int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += arr[i];
int S1 = (sum + K) / 2 ;
int [][] dp = new int [n+ 1 ][S1+ 1 ];
for ( int i = 0 ; i <= n; i++)
dp[i][ 0 ] = 1 ;
for ( int i = 1 ; i <= n; i++) {
for ( int j = 0 ; j <= S1; j++) {
if (arr[i- 1 ] <= j) {
dp[i][j] = dp[i- 1 ][j] + dp[i- 1 ][j-arr[i- 1 ]];
}
else {
dp[i][j] = dp[i- 1 ][j];
}
}
}
return dp[n][S1];
}
public static void main(String[] args) {
int [] arr = { 1 , 1 , 2 , 3 };
int N = arr.length;
int K = 1 ;
System.out.println(countSubsets(arr, K, N));
}
}
|
Python3
def countSubsets(arr, K, n):
sum = 0
for i in range (n):
sum + = arr[i]
S1 = ( sum + K) / / 2
dp = [[ 0 for j in range (S1 + 1 )] for i in range (n + 1 )]
for i in range (n + 1 ):
dp[i][ 0 ] = 1
for i in range ( 1 , n + 1 ):
for j in range (S1 + 1 ):
if arr[i - 1 ] < = j:
dp[i][j] = dp[i - 1 ][j] + dp[i - 1 ][j - arr[i - 1 ]]
else :
dp[i][j] = dp[i - 1 ][j]
return dp[n][S1]
if __name__ = = '__main__' :
arr = [ 1 , 1 , 2 , 3 ]
N = len (arr)
K = 1
print (countSubsets(arr, K, N))
|
C#
using System;
class GFG {
static int countSubsets( int [] arr, int K, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += arr[i];
int S1 = (sum + K) / 2;
int [, ] dp = new int [n + 1, S1 + 1];
for ( int i = 0; i <= n; i++)
dp[i, 0] = 1;
for ( int i = 1; i <= n; i++) {
for ( int j = 0; j <= S1; j++) {
if (arr[i - 1] <= j) {
dp[i, j] = dp[i - 1, j]
+ dp[i - 1, j - arr[i - 1]];
}
else {
dp[i, j] = dp[i - 1, j];
}
}
}
return dp[n, S1];
}
static void Main()
{
int [] arr = { 1, 1, 2, 3 };
int N = arr.Length;
int K = 1;
Console.WriteLine(countSubsets(arr, K, N));
}
}
|
Javascript
function countSubsets(arr, K, n)
{
let sum = 0;
for (let i = 0; i < n; i++) {
sum += arr[i];
}
let S1 = Math.floor((sum + K) / 2);
let dp = new Array(n + 1).fill().map(() => new Array(S1 + 1).fill(0));
for (let i = 0; i <= n; i++) {
dp[i][0] = 1;
}
for (let i = 1; i <= n; i++) {
for (let j = 0; j <= S1; j++) {
if (arr[i - 1] <= j) {
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[n][S1];
}
const arr = [1, 1, 2, 3];
const N = arr.length;
const K = 1;
console.log(countSubsets(arr, K, N));
|
Time Complexity: O(N*k)
Auxiliary Space: O(N*K)
Similar Reads
Split Array into min number of subsets with difference between each pair greater than 1
Given an array arr[] of size N, the task is to split the array into a minimum number of subset such that each pair of elements in each subset have the difference strictly greater than 1.Note: All elements in the array are distinct. Examples: Input: arr = {5, 10, 6, 50}Output: 2Explanation: Possible
5 min read
Split array into two subsequences having minimum count of pairs with sum equal to X
Given an array arr[] consisting of N integers and an integer X, the task is to split the array into two subsequences such that the number of pairs having a sum equal to X is minimum in both the arrays. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, X = 7 Output: The First Array is - 1 2 3The Second Ar
8 min read
Count of Subsets that can be partitioned into two non empty sets with equal Sum
Given an array Arr[] of size N, the task is to find the count of subsets of Arr[] that can be partitioned into two non-empty groups having equal sum. Examples: Input: Arr[] = {2, 3, 4, 5}Output: 2Explanation: The subsets are: {2, 3, 5} which can be split into {2, 3} and {5}{2, 3, 4, 5} which can be
15+ min read
Count ways to split array into two equal sum subarrays by replacing each array element to 0 once
Given an array arr[] consisting of N integers, the task is to count the number of ways to split the array into two subarrays of equal sum after changing a single array element to 0. Examples: Input: arr[] = {1, 2, -1, 3}Output: 4Explanation: Replacing arr[0] by 0, arr[] is modified to {0, 2, -1, 3}.
11 min read
Count pairs in an array such that the absolute difference between them is ≥ K
Given an array arr[] and an integer K, the task is to find the count of pairs (arr[i], arr[j]) from the array such that |arr[i] - arr[j]| ? K. Note that (arr[i], arr[j]) and arr[j], arr[i] will be counted only once.Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 3 All valid pairs are (1, 3), (1
6 min read
Count of elements such that difference between sum of left and right sub arrays is equal to a multiple of k
Given an array arr[] of length n and an integer k, the task is to find the number of indices from 2 to n-1 in an array having a difference of the sum of the left and right sub arrays equal to the multiple of the given number k. Examples: Input: arr[] = {1, 2, 3, 3, 1, 1}, k = 4 Output: 2 Explanation
7 min read
Count pairs in an array having sum of elements with their respective sum of digits equal
Given an array arr[] consisting of N positive integers, the task is to count the number of pairs in the array, say (a, b) such that sum of a with its sum of digits is equal to sum of b with its sum of digits. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Following are the pairs that sati
8 min read
Count ways to split array into two equal sum subarrays by changing sign of any one array element
Given an array arr[] consisting of N integers, the task is to count ways to split array into two subarrays of equal sum by changing the sign of any one array element. Examples: Input: arr[] = {2, 2, -3, 3}Output: 2Explanation:Changing arr[0] = 2 to arr[0] = -2, the array becomes {-2, 2, -3, 3}. Only
11 min read
Partition an array into two subsets with equal count of unique elements
Given an array arr[] consisting of N integers, the task is to partition the array into two subsets such that the count of unique elements in both the subsets is the same and for each element, print 1 if that element belongs to the first subset. Otherwise, print 2. If it is not possible to do such a
13 min read
Partition Array into two Arrays of equal size to Minimize Sum Difference
Given an integer array of size 2*n, partition the array into two arrays of equal length such that the absolute difference between the sums of these two arrays is minimum. Return this minimum difference. To partition the array, allocate each element to one of two arrays. Examples :Input: arr[] = {7,
15+ min read