Best approach to fit numbers

228 views Asked by At

I have the following set of integers {2,9,4,1,8}. I need to divide this set into two subsets so that the sum of the sets results in 14 and 10 respectively. In my example the answer is {2,4,8} and {9,1}. I am not looking for any code. I am pretty sure there must be a standard algorithm to solve this problem. Since i was not successful in googling and finding out that myself, i posted my query here. So what will be the best way to approach this problem?

My try was like this...

public class Test {
    public static void main(String[] args) {
        int[] input = {2, 9, 4, 1, 8};
        int target = 14;
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < input.length; i++) {
            stack.add(input[i]);
            for (int j = i+1;j<input.length;j++) {

                int sum = sumInStack(stack);

                if (sum < target) {
                    stack.add(input[j]);
                    continue;
                }

                if (target == sum) {
                    System.out.println("Eureka");
                }

                stack.remove(input[i]);
            }

        }
    }

    private static int sumInStack(Stack<Integer> stack) {
        int sum = 0;
        for (Integer integer : stack) {
            sum+=integer;
        }
        return sum;
    }
}

I know this approach is not even close to solve the problem

1

There are 1 answers

2
Caleb On

I need to divide this set into two subsets so that the sum of the sets results in 14 and 10 respectively.

If the subsets have to sum to certain values, then it had better be true that the sum of the entire set is the sum of those values, i.e. 14+10=24 in your example. If you only have to find the two subsets, then the problem isn't very difficult — find any subset that sums to one of those values, and the remaining elements of the set must sum to the other value.

For the example set you gave, {2,9,4,1,8}, you said that the answer is {9,1}, {2,4,8}, but notice that that's not the only answer; there's also {2,8}, {9,4,1}.