File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
src/Algorithms/Dynamic Programming Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments