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

后端 未结 4 626
青春惊慌失措
青春惊慌失措 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:40

    I would say first sort the array. Then your example would be: arr = {5, 19, 23, 36, 40, 41}. Then: 1) Take arr[0] and arr[i], where i = arr.Size. Sum it and record the difference between the sum and K, if the sum is lower than K. 2) If sum > K, do step 1, but instead of arr[i], use arr[i-1], because we want to lower our sum. If sum < K, do step 1, but instead of arr[0], use arr[1], because we want to increase our sum. Keep repeating step2, by either increasing or decreasing the indices, until the indices for the two elements are equal. Then, we know the pair of elements that result in the smallest difference between the sum and K.

    ----------------Edited for arbitrary number of elements in the solution----------------

    I believe you may need a tree. Here's what I'm thinking:

    1) Choose a number as your top node.

    2) For each number in the set, create a child node, and for each branch that was created, calculate the sum of that branch.

    3) If the sum is less then K, we branch again, creating child nodes for all the elements in the set. If the sum is greater than K, we stop, keep the difference between the sum and K(If sum < K). If we find a branch with a better sum, then we keep that branch. Repeat this process until all branches are done branching.

    Do steps 1-3 with different topnodes.

提交回复
热议问题