given N absolute values of integers find the combination of N/2 negative and N/2 positive values whose sum is closest to 0

后端 未结 5 1435
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 04:36

Let\'s say that I have an array of 10 numbers whose absolute value range can go from 1 to 10. Values can be repeated. An example of this could be

{2, 4, 2, 6, 9         


        
5条回答
  •  时光取名叫无心
    2021-01-21 05:13

    First sort the array, then put the biggest number into negative group and put Second-biggest into positive group. set a biggest number into positive group until sum of them is more than zero. Now set an other negative number.repeat it until you set 5 negative. This is greedy algorithm. Seems your problem is np-complete, it looks like AST problem but, size of your problem is limited to 10, so you can solve it by brute force search, you just have to check C(10,5)<10^5 possibilities and this number is small for today PCs.

    Also if was able to choose different size of sets, your problem was same as subset sum problem which can be solve in pseudo-polynomial time See it :1 , 2.

提交回复
热议问题