Skip to content

Commit d8536ec

Browse files
authored
Create 07 Minimum subset sum difference.cpp
1 parent c1f3249 commit d8536ec

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
vector<int> isSubsetPoss(int arr[], int n, int sum) {
5+
bool t[n + 1][sum + 1]; // DP - matrix
6+
// initialization
7+
for (int i = 0; i <= n; i++) {
8+
for (int j = 0; j <= sum; j++) {
9+
if (i == 0)
10+
t[i][j] = false;
11+
if (j == 0)
12+
t[i][j] = true;
13+
}
14+
}
15+
// taking from the 2nd row and 2nd column
16+
for (int i = 1; i <= n; i++) {
17+
for (int j = 1; j <= sum; j++) {
18+
if (arr[i - 1] <= j)
19+
t[i][j] = t[i - 1][j - arr[i - 1]] || t[i - 1][j]; // include or exclude
20+
else
21+
t[i][j] = t[i - 1][j]; // exclude
22+
}
23+
}
24+
25+
vector<int> v; // contains all subset sums possible with n elements // creating a vector varible to store all the element of the last row
26+
for (int j = 0; j <= sum; j++)
27+
if (t[n][j] == true)
28+
v.push_back(j);
29+
30+
return v;
31+
}
32+
33+
int MinSubsetSumDiff(int arr[], int n) {
34+
int range = 0;
35+
for (int i = 0; i < n; i++)
36+
range += arr[i]; // taking sum of the array for range
37+
38+
vector<int> v = isSubsetPoss(arr, n, range);
39+
int mn = INT_MAX;
40+
for (int i = 0; i < v.size(); i++)
41+
mn = min(mn, abs(range - 2 * v[i])); // taking minimum from the last row
42+
43+
return mn;
44+
}
45+
46+
signed main() {
47+
int n; cin >> n;
48+
int arr[n];
49+
for (int i = 0; i < n; i++)
50+
cin >> arr[i];
51+
52+
cout << MinSubsetSumDiff(arr, n) << endl;
53+
return 0;
54+
}

0 commit comments

Comments
 (0)