-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMinimumSumPartition.cpp
More file actions
60 lines (55 loc) · 1.24 KB
/
Copy pathMinimumSumPartition.cpp
File metadata and controls
60 lines (55 loc) · 1.24 KB
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
/*
GFG-Minimum sum partition
Given an integer array arr of size N, the task is to divide it into two sets S1 and S2 such that the
absolute difference between their sums is minimum and find the minimum difference
Example 1:
Input: N = 4, arr[] = {1, 6, 11, 5}
Output: 1
Example 2:
Input: N = 2, arr[] = {1, 4}
Output: 3
Extension of subset sum problem-
*/
class Solution{
public:
int minDiffernce(int arr[], int n)
{
sort(arr,arr+n);
int sum=0;
sum=accumulate(arr,arr+n,sum);
int temp=sum;
sum=(sum+1)/2;
bool **Dp=(bool **)malloc((n+1)*sizeof(bool *));
for(int i=0;i<=n;i++)
Dp[i]=(bool *)malloc((sum+1)*sizeof(bool));
for(int i=0;i<=n;i++)
Dp[i][0]=true;
for(int i=1;i<=sum;i++)
Dp[0][i]=false;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=sum;j++)
{
if(j<arr[i-1])
Dp[i][j]=Dp[i-1][j];
else
{
Dp[i][j]=Dp[i-1][j]||Dp[i-1][j-arr[i-1]];
}
}
}
int ans=0;
for(int i=sum;i>=0;i--)
{
if(Dp[n][i])
{
ans=i;
break;
}
}
for(int i=0;i<=n;i++)
free(Dp[i]);
free(Dp);
return abs(ans-(temp-ans));
}
};