-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin_diff_between_subset.txt
66 lines (57 loc) · 1.46 KB
/
min_diff_between_subset.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// A Recursive C program to solve minimum sum partition
// problem.
#include <bits/stdc++.h>
using namespace std;
// Returns the minimum value of the difference of the two sets.
int findMin(int arr[], int n)
{
// Calculate sum of all elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// Create an array to store results of subproblems
bool dp[n+1][sum+1];
// Initialize first column as true. 0 sum is possible
// with all elements.
for (int i = 0; i <= n; i++)
dp[i][0] = true;
// Initialize top row, except dp[0][0], as false. With
// 0 elements, no other sum except 0 is possible
for (int i = 1; i <= sum; i++)
dp[0][i] = false;
// Fill the partition table in bottom up manner
for (int i=1; i<=n; i++)
{
for (int j=1; j<=sum; j++)
{
// If i'th element is excluded
dp[i][j] = dp[i-1][j];
// If i'th element is included
if (arr[i-1] <= j)
dp[i][j] |= dp[i-1][j-arr[i-1]];
}
}
// Initialize difference of two sums.
int diff = INT_MAX;
// Find the largest j such that dp[n][j]
// is true where j loops from sum/2 t0 0
for (int j=sum/2; j>=0; j--)
{
// Find the
if (dp[n][j] == true)
{
diff = sum-2*j;
break;
}
}
return diff;
}
// Driver program to test above function
int main()
{
int arr[] = {3, 1, 4, 2, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "The minimum difference between 2 sets is "
<< findMin(arr, n);
return 0;
}