divide list in two parts that their sum closest to each other

前端 未结 3 1277
深忆病人
深忆病人 2020-12-09 12:56

This is a hard algorithms problem that :

Divide the list in 2 parts (sum) that their sum closest to (most) each other

list length is 1 <

3条回答
  •  佛祖请我去吃肉
    2020-12-09 13:51

    This problem is at least as hard as the NP-complete problem subset sum. Your algorithm is a greedy algorithm. This type of algorithm is fast, and can generate an approximate solution quickly but it cannot find the exact solution to an NP-complete problem.

    A brute force approach is probably the simplest way to solve your problem, although it is will be to slow if there are too many elements.

    • Try every possible way of partitioning the elements into two sets and calculate the absolute difference in the sums.
    • Choose the partition for which the absolute difference is minimal.

    Generating all the partitions can be done by considering the binary representation of each integer from 0 to 2^n, where each binary digit determines whether the correspending element is in the left or right partition.

提交回复
热议问题