Skip to content

Commit 4ac4a62

Browse files
authored
Merge pull request TheAlgorithms#1338 from swatiprajapati08/patch-1
Minimum sum partition
2 parents e3a78a6 + 5d77174 commit 4ac4a62

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// Partition a set into two subsets such that the difference of subset sums is minimum
2+
3+
/*
4+
Input: arr[] = {1, 6, 11, 5}
5+
Output: 1
6+
Explanation:
7+
Subset1 = {1, 5, 6}, sum of Subset1 = 12
8+
Subset2 = {11}, sum of Subset2 = 11
9+
10+
Input: arr[] = {36, 7, 46, 40}
11+
Output: 23
12+
Explanation:
13+
Subset1 = {7, 46} ; sum of Subset1 = 53
14+
Subset2 = {36, 40} ; sum of Subset2 = 76
15+
*/
16+
17+
import java.util.*;
18+
import java.lang.*;
19+
import java.io.*;
20+
class GFG
21+
{
22+
public static void main (String[] args)
23+
{
24+
Scanner sc=new Scanner(System.in);
25+
int t=sc.nextInt();
26+
while(t-->0)
27+
{
28+
int n=sc.nextInt();
29+
int arr[]=new int[n];
30+
int sum=0;
31+
for(int i=0;i<n;i++)
32+
{
33+
arr[i]=sc.nextInt();
34+
sum+=arr[i];
35+
}
36+
int ans[]=new int[sum];
37+
ans=subset(arr,sum);
38+
int min=Integer.MAX_VALUE;
39+
for(int i=0;i<ans.length;i++)
40+
min=Math.min(min,(sum-2*ans[i]));
41+
42+
System.out.println(min);
43+
44+
45+
}
46+
}
47+
static int[] subset(int arr[],int sum)
48+
{
49+
int n=arr.length;
50+
boolean dp[][]=new boolean[n+1][sum+1];
51+
for(int i=0;i<=n;i++)
52+
dp[i][0]=true;
53+
for(int i=1;i<=sum;i++)
54+
dp[0][i]=false;
55+
56+
// subset sum concept
57+
for(int i=1;i<=n;i++)
58+
{
59+
for(int j=1;j<=sum;j++)
60+
{
61+
if(arr[i-1]<=j)
62+
dp[i][j]=dp[i-1][j-arr[i-1]] || dp[i-1][j];
63+
else
64+
dp[i][j]=dp[i-1][j];
65+
}
66+
}
67+
68+
//storing last dp column whose value is true till sum/2
69+
int index[]=new int[sum];
70+
int p=0;
71+
for(int i=0;i<=sum/2;i++)
72+
{
73+
if(dp[n][i]==true)
74+
index[p++]=i;
75+
}
76+
return index;
77+
}
78+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy