1

I have an array such as below:

int[] numberArray = {9,2,1,5,6};

I want to devise a method that will take an integer as an argument and return true/false depending if the argument can be achieved by summing any of the numbers in that array.

public boolean sumCheck (int sum) {
    // ...
}

For example, if sum were 5, sumCheck would return true since numberArray[3] == 5. If sum were 12, sumCheck would return true since numberArray[0]+numberArray[1]+numberArray[2] == 12. It would not return true, however, if sum were 4, as no combination of numberArray elements can sum to this number.

0

2 Answers 2

4

This is the subset sum problem, which is NP-complete. However, you can find a pseudo-polynomial time algorithm (a variant of knapsack, using DP) on the Wiki page.

Sign up to request clarification or add additional context in comments.

Comments

1

Check http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/..it explains your problem in a nice way. First brute force then dp solution is there.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.