Skip to content

Commit a09adb1

Browse files
authored
Create 08 Count the number of subset with given difference.cpp
1 parent e93a132 commit a09adb1

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int CountSubsetsWithSum(int arr[], int n, int sum) {
5+
int t[n + 1][sum + 1]; // DP - matrix
6+
// initialization
7+
// here we are setting 1st row and 1st column
8+
// i denotes the size of the array
9+
// j denotes the target sum (subset sum)
10+
for (int i = 0; i <= n; i++) {
11+
for (int j = 0; j <= sum; j++) {
12+
if (i == 0) // when array(i) is empty than there is no meaning of sum of elements so return count of subset as 0;
13+
t[i][j] = 0;
14+
if (j == 0) // when sum(j) is zero and there is always a chance of empty subset so return count as 1;
15+
t[i][j] = 1;
16+
}
17+
}
18+
19+
for (int i = 1; i <= n; i++) {
20+
for (int j = 1; j <= sum; j++) {
21+
if (arr[i - 1] <= j) // when element in the list is less then target sum
22+
t[i][j] = t[i - 1][j - arr[i - 1]] + t[i - 1][j]; // either exclude or inxlude and add both of them to get final count
23+
else
24+
t[i][j] = t[i - 1][j]; // exclude when element in the list is greater then the sum
25+
}
26+
}
27+
28+
return t[n][sum]; // finally return the last row and last column element
29+
}
30+
31+
int CountSubsetsWithDiff(int arr[], int n, int diff) {
32+
int sumOfArray = 0;
33+
for (int i = 0; i < n; i++)
34+
sumOfArray += arr[i]; // taking sum of the array
35+
36+
if ((sumOfArray + diff) % 2 != 0)
37+
return 0;
38+
else
39+
return CountSubsetsWithSum(arr, n, (sumOfArray + diff) / 2);// we will get the number of array(subset) with particular sum
40+
}
41+
42+
signed main() {
43+
int n; cin >> n;
44+
int arr[n];
45+
for (int i = 0; i < n; i++)
46+
cin >> arr[i];
47+
int diff; cin >> diff;
48+
49+
cout << CountSubsetsWithDiff(arr, n, diff) << endl;
50+
return 0;
51+
}

0 commit comments

Comments
 (0)