File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ public class MinimumSubsetSumDifference {
2+ public static int minSubsetSumDifference (int []arr , int n ) {
3+ int k = 0 ;
4+ for (int i = 0 ; i <n ; i ++){
5+ k += arr [i ];
6+ }
7+
8+ int bestSubsetSum = (int ) k /2 ;
9+
10+ boolean dp [][] = new boolean [n ][bestSubsetSum +1 ];
11+
12+ for (int i = 0 ; i <n ; i ++){
13+ dp [i ][0 ] = true ;
14+ }
15+
16+ for (int j = 0 ; j <bestSubsetSum +1 ; j ++){
17+ if (j == arr [0 ]){
18+ dp [0 ][j ] = true ;
19+ }
20+ }
21+
22+ for (int i = 1 ; i <n ; i ++){
23+ for (int j = 1 ; j <bestSubsetSum +1 ; j ++){
24+ if (arr [i ] == j ){
25+ dp [i ][j ] = true ;
26+ }
27+ if (j >= arr [i ]){
28+ dp [i ][j ] = dp [i -1 ][j ] || dp [i -1 ][j -arr [i ]];
29+ }
30+ else {
31+ dp [i ][j ] = dp [i -1 ][j ];
32+ }
33+ }
34+ }
35+
36+ int s1 = 0 ;
37+ int s2 = 0 ;
38+ for (int j = 0 ; j <bestSubsetSum +1 ; j ++){
39+ if (dp [n -1 ][j ] == true ){
40+ s1 = j ;
41+ s2 = k -s1 ;
42+ }
43+ }
44+ return Math .abs (s1 -s2 );
45+ }
46+ }
You can’t perform that action at this time.
0 commit comments