Linear algorithm to find minimum subset sum over a threshold

前端 未结 2 651
孤城傲影
孤城傲影 2021-01-14 18:04

I have a collection of N positive integers, each bounded by a (relatively small) constant C. I want to find a subset of these numbers with the smallest sum greater than (or

相关标签:
2条回答
  • 2021-01-14 18:36

    Well one solution is to:

    T = {0}
    
    for x in V
       for t in T
           T.insert(x+t)
    
    for i in K to max(T)
       if (T.contains(i))
           return i
    
    fail
    

    This gives you the size of the subset, but you can adapt to output the members.

    The maximum size of T is O(N) (because of C bound), so the running time is O(N^2) and the space is O(N). You can use a bit array of length NC as the backing store of T.

    0 讨论(0)
  • 2021-01-14 18:45

    Pisinger's algorithm gives you the largest sum less than or equal to the capacity of the knapsack. To solve your problem, use Pisinger to figure out what not to put in the subset. Formally, let the items be w_1, ..., w_n and the minimum be K. Give w_1, ..., w_n and w_1 + ... + w_n - K to Pisinger, then take every item that Pisinger does not.

    0 讨论(0)
提交回复
热议问题