In Java, how should I find the closest (or equal) possible sum of an Array\'s elements to a particular value K?
For example, for the array {19,23,41,5,40,36} and K=4
You can see it as a n-choose-k problem for all possible k so the complexity is exponential.
K. The set should include i numbers, for i=1; i<=N; i++. To implement this, for each i just take all the n-choose-i combinations of the numbers in the array.finalResult variable with the best set of numbers found so far and their sum.finalResult and update it if necessary.It reminds me of the Knapsack problem, so you may want to take a look at it.