3

I am trying to solve this problem where you are given a list of integers and you are expected to find 2 subsets of that list where the sum of the lists is minimized, the catch is the subsets must be the same length, or if it is an odd number input than one subset can have an additional number. I wrote an algorithm that is correct for some inputs, but wrong for others and I do not know where I am going wrong here

Examples of my inputs and outputs:

input [4,6,17,3,2,5,10] output -> [10,6,5,2] , [17,4,3] this is the correct output

input [1,2,3,100,5,6] output -> [6,5,4] , [100,2,1] this is the correct output

input [1,2,5,10,15,3] output -> [10,5,2] , [15,3,1] this is incorrect, the output should be [15,2,1] , [10,5,3]

public static String closesSums(int[] input){
        List<Integer> list = new ArrayList<>();
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        for(int i = 0; i < input.length; i++){
            list.add(input[i]);
        }
        
        Collections.sort(list);
        int dif = 0;
        for(int i = list.size() - 1; i >= 0; i--){
            if(dif > 0 && ((list1.size() < (list.size() % 2) + list.size() / 2)){
                dif -= list.get(i);
                list1.add(list.get(i));
            } else {
                dif += list.get(i);
                list2.add(list.get(i));
            }
        }
        
        return list1.toString() + list2.toString();
    }

I don't know if this is the wrong approach to the problem or if I am just missing something in my code, can someone help out here?

Noah Iarrobino
  • 1,435
  • 1
  • 10
  • 31
  • So basically you're looking for an algorithm to partition an array into two subarrays, such that the sum of them is as close to each other as possible? Also in the second example, there's a three on the left side, but a four on the right side. I suppose that's just a typo? –  Dec 29 '20 at 16:01
  • exactly, but the subarrays must be the same size, or if odd number input than one subarray can have 1 extra element – Noah Iarrobino Dec 29 '20 at 16:03
  • I think you need to split the set into the outer two quartiles and the inner two quartiles after sorting, at least when the set size is a nice multiple of 4. – Jems Dec 29 '20 at 16:25
  • 1
    You are using a greedy approach to an NP-complete problem. That is only going to work sometimes. The approach that I describe in https://stackoverflow.com/a/65314921/585411 can be adapted to work all of the time. – btilly Dec 29 '20 at 17:02
  • 1
    that looks painful – Noah Iarrobino Dec 29 '20 at 19:40

0 Answers0