How do I find the closest possible sum of an Array's elements to a particular value?

后端 未结 4 701
青春惊慌失措
青春惊慌失措 2021-01-02 07:31

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

4条回答
  •  灰色年华
    2021-01-02 07:41

    You can see it as a n-choose-k problem for all possible k so the complexity is exponential.

    1. Find a set of numbers that sum at most up to 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.
    2. Keep a finalResult variable with the best set of numbers found so far and their sum.
    3. Compare each sub-result of step 1 with the finalResult and update it if necessary.

    It reminds me of the Knapsack problem, so you may want to take a look at it.

提交回复
热议问题