The smallest subarray sum with the sum greater than the specified value

Input array N positive numbers and the value of X , for which N is small compared with X
Conclusion : Subarray the sum of all his numbers equal to the Y> X , so that there is no other subarray with the sum of its numbers is greater than X but less than the Y .

Is there a polynomial solution to this question? If so, can you introduce it?

+4
source share
3 answers

As other answers show, this is an NP-Complete problem called “ Backpack Problem . So there is no polynomial solution. But it has a pseudo-polynomial time algorithm. This explains what the pseudo-polynomial is .

Visual explanation of the algorithm .

And some code .

If this is related to work (I have already encountered this problem several times, in different masks), I suggest introducing additional restrictions to simplify it. If this were a general question, you can also check out other issues with NP-Complete. One such list.

Change 1:

AliVar . Y > X, Y < X. , . , Y > X, , S < ( - X). - . ,

  • S < ( - X)
  • .
  • Y > X
+3

A - . O(X*N):

initialize set S = {0}
initialize map<int, int> parent
best_sum = inf
best_parent = -1
for a in A
     Sn = {}
     for s in S
         t = s + a
         if t > X and t < best_sum
             best_sum = t
             best_parent = s
         end if
         if t <= X
             Sn.add(t)
             parent[t] = s
         end if
     end for
     S = S unite with Sn
end for

, :

Subarray = {best_sum - best_parent}
t = best_parent
while t in parent.keys()
    Subarray.add(t-parent[t])
    t = parent[t]
end while
print Subarray

. (, ), X. A A , . S = S unite with Sn S , A , Sn , A.

S , true, . , X.

, O(X*N) O(X).

+2

, NP-hard, . : S = {x1,..., xn} t. d - xi xj. S '= {x1 + d/n,..., xn + d/n} . , ; .. D ' S' Y > t, . D ' D. : 1) Y = t + | D | * d/n, , D . 2) Y > t + | D | * d/n, , . 3) Y < t + | D | * d/n. t = Y . t , . , .

+1
source

Source: https://habr.com/ru/post/1629012/


All Articles