# Count of Subsets with given Difference

• Difficulty Level : Hard
• Last Updated : 19 Sep, 2022

Given an array arr[] of size N and a given difference diff, the task is to count the number of partitions that we can perform such that the difference between the sum of the two subsets is equal to the given difference.

Note: A partition in the array means dividing an array into two parts say S1 and S2 such that the union of S1 and S2 is equal to the original array and each element is present in only of the subsets.

Examples:

Input: N = 4, arr[] = [5, 2, 6, 4], diff = 3
Output: 1
Explanation: We can only have a single partition which is shown below:
{5, 2} and {6, 4} such that S1 = 7 and S2 = 10 and thus the difference is 3

Input: N = 5, arr[] = [1, 2, 3, 1, 2], diff = 1
Output: 5
Explanation: We can have five partitions which is shown below
{1, 3, 1} and {2, 2} – S1 = 5, S2 = 4
{1, 2, 2} and {1, 3} – S1 = 5, S2 = 4
{3, 2} and {1, 1, 2} – S1 = 5, S2 = 4
{1, 2, 2} and {1, 3} – S1 = 5, S2 = 4
{3, 2} and {1, 1, 2} – S1 = 5, S2 = 4

Naive Approach: The problem can be solved based on the following mathematical idea:

• Suppose the array is partiotioned in two subsets with sum S1 and S2, so we know that,
• S1 + S2  is the total sum array nums
• S1 – S2 is the given diff
• Subtracting the two equations we would get,
• sum – diff = (S1 + S2) – (S1 – S2) = 2*S2 . So, S2 = ( sum – diff ) / 2
• From this we get the idea that an element X can be partiotioned in only one way when the difference between the two partitions is given.
• Therefore, in this case of array the total number of possible ways depends on the number of possible ways to create a subset having sum S2.

So we can use the concept of recursion to generate all possible subsets with sum S2. For each element there are two choices: either be a part of the subset S2 or not.

In the above idea, there are conditions visible that must be satisfied for the subset to exist:

• The difference between array sum and diff must be a positive number and
• This value must be an even number (As this is the same as 2*S2).

Time Complexity: O(2N)
Auxiliary Space: O(N)

Efficient Approach: The idea is similar as the naive one. But here we will use the idea of dynamic programming to optimize the time complexity.

Upon close observation, it can be seen that any state can be uniquely defined unsing two parameters, one parameter represents the index, and the other one represents the sum (S2) of the subset formed using elements from the starting till that index.

So, we can count the number of ways to form the subset from each state and can reuse them to avoid repeated calculations.

Follow the steps mentioned below to implement the approach:

• Calculate the sum of  the array.
• Create a 2 dimensional array dp[][] with dimension (N * array sum) to store the calculated value of each state.
• Traverse the array using recursion and generate two calls.
• If the value for the state is already calculated, reuse the value.
• Otherwise there are two cases:
• If adding the current element will not make the currentSum more than S2, then generate two calls, one with the current element added to the currentSum and the other without adding it.
• If adding the current element increases currentSum above S2, then we only generate one call without adding the current element.
• If the currentSum is equal to S2 then we return 1.
• Return the final value received in this way as the answer.

Below is the implementation of the above approach.

## C++

 `// C++ code to implement the approach`   `#include ` `using` `namespace` `std;` `int` `dp;`   `// Function to implement dynamic programming concept` `// to count the total number of possible ways` `int` `countSubsets(vector<``int``>& v, ``int` `i, ``int` `S2,` `                 ``int` `currentSum)` `{` `    ``if` `(currentSum == S2) {` `        ``return` `1;` `    ``}` `    ``if` `(i >= v.size()) {` `        ``return` `0;` `    ``}` `    ``if` `(dp[i][currentSum] != -1) {` `        ``return` `dp[i][currentSum];` `    ``}` `    ``if` `(currentSum + v[i] > S2) {` `        ``return` `dp[i][currentSum]` `               ``= countSubsets(v, i + 1, S2, currentSum);` `    ``}` `    ``else` `{` `        ``return` `dp[i][currentSum]` `               ``= countSubsets(v, i + 1, S2,` `                              ``currentSum + v[i])` `                 ``+ countSubsets(v, i + 1, S2, currentSum);` `    ``}` `}` `int` `countSub(vector<``int``>& vp, ``int` `N, ``int` `diff)` `{` `    ``int` `sum = 0; ``// Calculating total sum` `    ``for` `(``auto``& value : vp)` `        ``sum += value;` `    ``// edge cases` `    ``if` `(sum - diff < 0 || (sum - diff) % 2 == 1) {` `        ``return` `0;` `    ``}` `    ``// let the two subsets be having sum s1, s2` `    ``// s1-s2 = D, where D is the difference` `    ``// s1+s2 = Sum, where Sum is total Sum` `    ``// s2 = (Sum-diff)/2` `    ``return` `countSubsets(vp, 0, (sum - diff) / 2, 0);` `}`   `// Driver code` `int` `main()` `{` `    ``int` `N = 5;` `    ``vector<``int``> arr = { 1, 2, 3, 1, 2 };` `    ``int` `diff = 1;` `    ``memset``(dp, -1, ``sizeof``(dp));`   `    ``// Function call` `    ``cout << countSub(arr, N, diff) << endl;` `    ``return` `0;` `}`

## Java

 `// Java program for above approach` `import` `java.util.*;` `import` `java.util.Arrays;`   `class` `GFG` `{`   `static` `int` `dp[][] = ``new` `int``[``1001``][``10000``];`   `// Function to implement dynamic programming concept` `// to count the total number of possible ways` `static` `int` `countSubsets(``int``[] v, ``int` `i, ``int` `S2,` `                 ``int` `currentSum)` `{` `    ``if` `(currentSum == S2) {` `        ``return` `1``;` `    ``}` `    ``if` `(i >= v.length) {` `        ``return` `0``;` `    ``}` `    ``if` `(dp[i][currentSum] != -``1``) {` `        ``return` `dp[i][currentSum];` `    ``}` `    ``if` `(currentSum + v[i] > S2) {` `        ``return` `dp[i][currentSum]` `               ``= countSubsets(v, i + ``1``, S2, currentSum);` `    ``}` `    ``else` `{` `        ``return` `dp[i][currentSum]` `               ``= countSubsets(v, i + ``1``, S2,` `                              ``currentSum + v[i])` `                 ``+ countSubsets(v, i + ``1``, S2, currentSum);` `    ``}` `}` `static` `int` `countSub(``int``[] vp, ``int` `N, ``int` `diff)` `{` `    ``int` `sum = ``0``; ``// Calculating total sum` `    ``for` `(``int` `value : vp)` `        ``sum += value;` `    ``// edge cases` `    ``if` `(sum - diff < ``0` `|| (sum - diff) % ``2` `== ``1``) {` `        ``return` `0``;` `    ``}` `    ``// let the two subsets be having sum s1, s2` `    ``// s1-s2 = D, where D is the difference` `    ``// s1+s2 = Sum, where Sum is total Sum` `    ``// s2 = (Sum-diff)/2` `    ``return` `countSubsets(vp, ``0``, (sum - diff) / ``2``, ``0``);` `}`     `// Driver code` `public` `static` `void` `main(String[] args)` `{` `    ``int` `N = ``5``;` `    ``int``[] arr = { ``1``, ``2``, ``3``, ``1``, ``2` `};` `    ``int` `diff = ``1``;` `    ``for``(``int` `i = ``0``; i <``1001``; i++)` `    ``{` `        ``for``(``int` `j = ``0``; j <``10000``; j++)` `        ``{` `            ``dp[i][j] = -``1``;` `        ``}` `    ``}`   `    ``// Function call` `    ``System.out.print(countSub(arr, N, diff));` `}` `}`

## Python3

 `# python3 code to implement the approach`   `dp ``=` `[[``-``1` `for` `_ ``in` `range``(``10000``)] ``for` `_ ``in` `range``(``1001``)]`   `# Function to implement dynamic programming concept` `# to count the total number of possible ways` `def` `countSubsets(v, i, S2, currentSum):` `    ``global` `dp` `    ``if` `(currentSum ``=``=` `S2):` `        ``return` `1`   `    ``if` `(i >``=` `len``(v)):` `        ``return` `0`   `    ``if` `(dp[i][currentSum] !``=` `-``1``):` `        ``return` `dp[i][currentSum]`   `    ``if` `(currentSum ``+` `v[i] > S2):` `        ``dp[i][currentSum] ``=` `countSubsets(v, i ``+` `1``, S2, currentSum)` `        ``return` `dp[i][currentSum]`   `    ``else``:` `        ``dp[i][currentSum] ``=` `countSubsets(` `            ``v, i ``+` `1``, S2, currentSum ``+` `v[i]) ``+` `countSubsets(v, i ``+` `1``, S2, currentSum)` `        ``return` `dp[i][currentSum]`     `def` `countSub(vp, N, diff):`   `    ``sum` `=` `0`  `# Calculating total sum` `    ``for` `value ``in` `vp:` `        ``sum` `+``=` `value` `    ``# edge cases` `    ``if` `(``sum` `-` `diff < ``0` `or` `(``sum` `-` `diff) ``%` `2` `=``=` `1``):` `        ``return` `0`   `    ``# let the two subsets be having sum s1, s2` `    ``# s1-s2 = D, where D is the difference` `    ``# s1+s2 = Sum, where Sum is total Sum` `    ``# s2 = (Sum-diff)/2` `    ``return` `countSubsets(vp, ``0``, (``sum` `-` `diff) ``/``/` `2``, ``0``)`   `# Driver code` `if` `__name__ ``=``=` `"__main__"``:`   `    ``N ``=` `5` `    ``arr ``=` `[``1``, ``2``, ``3``, ``1``, ``2``]` `    ``diff ``=` `1`   `    ``# Function call` `    ``print``(countSub(arr, N, diff))` `    `  `    ``# This code is contributed by rakeshsahni`

## C#

 `// C# code to implement the approach` `using` `System;` `class` `GFG {`   `static` `int``[,] dp = ``new` `int``[1001, 10000];`   `// Function to implement dynamic programming concept` `// to count the total number of possible ways` `static` `int` `countSubsets(``int``[] v, ``int` `i, ``int` `S2,` `                 ``int` `currentSum)` `{` `    ``if` `(currentSum == S2) {` `        ``return` `1;` `    ``}` `    ``if` `(i >= v.Length) {` `        ``return` `0;` `    ``}` `    ``if` `(dp[i, currentSum] != -1) {` `        ``return` `dp[i, currentSum];` `    ``}` `    ``if` `(currentSum + v[i] > S2) {` `        ``return` `dp[i, currentSum]` `               ``= countSubsets(v, i + 1, S2, currentSum);` `    ``}` `    ``else` `{` `        ``return` `dp[i, currentSum]` `               ``= countSubsets(v, i + 1, S2,` `                              ``currentSum + v[i])` `                 ``+ countSubsets(v, i + 1, S2, currentSum);` `    ``}` `}` `static` `int` `countSub(``int``[] vp, ``int` `N, ``int` `diff)` `{` `    ``int` `sum = 0; ``// Calculating total sum` `    ``foreach` `(``int` `value ``in` `vp)` `        ``sum += value;` `    ``// edge cases` `    ``if` `(sum - diff < 0 || (sum - diff) % 2 == 1) {` `        ``return` `0;` `    ``}` `    ``// let the two subsets be having sum s1, s2` `    ``// s1-s2 = D, where D is the difference` `    ``// s1+s2 = Sum, where Sum is total Sum` `    ``// s2 = (Sum-diff)/2` `    ``return` `countSubsets(vp, 0, (sum - diff) / 2, 0);` `}`   `// Driver Code` `public` `static` `void` `Main()` `{` `    ``int` `N = 5;` `    ``int``[] arr = { 1, 2, 3, 1, 2 };` `    ``int` `diff = 1;` `    ``for``(``int` `i = 0; i <1001; i++)` `    ``{` `        ``for``(``int` `j = 0; j <10000; j++)` `        ``{` `            ``dp[i, j] = -1;` `        ``}` `    ``}`   `    ``// Function call` `    ``Console.WriteLine(countSub(arr, N, diff));` `}` `}`   `// This code is contributed by code_hunt.`

## Javascript

 ``

Output

`5`

Time Complexity: O(N*(sum of the subset))
Auxiliary Space: O(N * array sum)

My Personal Notes arrow_drop_up
Recommended Articles
Page :