How to divide a set into two subsets such that difference between the sum of numbers in two sets is minimal?

前端 未结 18 708
攒了一身酷
攒了一身酷 2020-11-27 10:55

Given a set of numbers, divide the numbers into two subsets such that difference between the sum of numbers in two subsets is minimal.

T

18条回答
  •  情歌与酒
    2020-11-27 11:33

    We can use Dynamic Programming (similar to the way we find if a set can be partitioned into two equal sum subsets). Then we find the max possible sum, which will be our first partition. Second partition will be the difference of the total sum and firstSum. Answer will be the difference of the first and second partitions.

    public int minDiffernce(int set[]) {      
        int sum = 0;
        int n = set.length;
        for(int i=0; ij) dp[i][j] = dp[i-1][j];
                else dp[i][j] = dp[i-1][j] || dp[i-1][j-set[i-1]];
            }
        }
    
        // we now find the max sum possible starting from target
        int firstPart = 0;
        for(int j = target; j>=0; j--){
            if(dp[n][j] == true) {
                firstPart = j; break;
            }
        }
    
        int secondPart = sum - firstPart;
        return Math.abs(firstPart - secondPart);
    }
    

提交回复
热议问题