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?