Skip to content

Commit 0cd3e69

Browse files
authored
Merge pull request #435 from RAUNAK-PANDEY/Raunak
minimum difference of two subset using C++ #415
2 parents 8459bcd + 025cd5e commit 0cd3e69

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
//Link : https://www.interviewbit.com/problems/minimum-difference-subsets/
2+
/*
3+
Problem Description
4+
5+
Given an integer array A containing N integers.
6+
7+
You need to divide the array A into two subsets S1 and S2 such that the absolute difference between their sums is minimum.
8+
9+
Find and return this minimum possible absolute difference.
10+
11+
NOTE:
12+
13+
Subsets can contain elements from A in any order (not necessary to be contiguous).
14+
Each element of A should belong to any one subset S1 or S2, not both.
15+
It may be possible that one subset remains empty.
16+
17+
18+
Problem Constraints
19+
1 <= N <= 100
20+
21+
1 <= A[i] <= 100
22+
23+
24+
25+
Input Format
26+
First and only argument is an integer array A.
27+
28+
29+
30+
Output Format
31+
Return an integer denoting the minimum possible difference among the sums of two subsets.
32+
33+
34+
35+
Example Input
36+
Input 1:
37+
38+
A = [1, 6, 11, 5]
39+
40+
41+
Example Output
42+
Output 1:
43+
44+
1
45+
46+
47+
Example Explanation
48+
Explanation 1:
49+
50+
Subset1 = {1, 5, 6}, sum of Subset1 = 12
51+
Subset2 = {11}, sum of Subset2 = 11*/
52+
53+
int Solution::solve(vector<int> &A) {
54+
int sum = 0,N=A.size();
55+
for (int i = 0; i < A.size(); i++)
56+
sum += A[i];
57+
58+
bool dp[N+1][sum+1];
59+
60+
for(int i=0;i<N+1;i++)
61+
{
62+
for(int j=0;j<sum+1;j++)
63+
{
64+
65+
if(j==0) dp[i][j]= true;
66+
else if(i==0) dp[i][j]= false;
67+
68+
else if(A[i-1] <= j)
69+
{
70+
dp[i][j] = dp[i-1][j-A[i-1]] || dp[i-1][j];
71+
}
72+
else dp[i][j] = dp[i-1][j];
73+
}
74+
}
75+
// Initialize difference of two sums.
76+
int diff = INT_MAX;
77+
78+
// Find the largest j such that dp[n][j]
79+
// is true where j loops from sum/2 t0 0
80+
for (int j=sum/2; j>=0; j--)
81+
{
82+
// Find the
83+
if (dp[N][j] == true)
84+
{
85+
diff = sum-2*j;
86+
break;
87+
}
88+
}
89+
return diff;
90+
}

0 commit comments

Comments
 (0)