Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the array “sum and/or sub” to `x`?

Goal

I would like to write an algorithm (in C) which returns TRUE or FALSE (1 or 0) depending whether the array A given in input can “sum and/or sub” to x (see below for clarification). Note that all values of A are integers bounded between [1,x-1] that were randomly (uniformly) sampled.

Clarification and examples

By “sum and/or sub”, I mean placing "+" and "-" in front of each element of array and summing over. Let's call this function SumSub.

int SumSub (int* A,int x)
{
...
}

SumSub({2,7,5},10)

should return TRUE as 7-2+5=10. You will note that the first element of A can also be taken as negative so that the order of elements in A does not matter.

SumSub({2,7,5,2},10)

should return FALSE as there is no way to “sum and/or sub” the elements of array to reach the value of x. Please note, this means that all elements of A must be used.

Complexity

Let n be the length of A. Complexity of the problem is of order O(2^n) if one has to explore all possible combinations of pluses and minus. However, some combinations are more likely than others and therefore are worth being explored first (hoping the output will be TRUE). Typically, the combination which requires substracting all elements from the largest number is impossible (as all elements of A are lower than x). Also, if n>x, it makes no sense to try adding all the elements of A.

Question

How should I go about writing this function?

like image 460
Remi.b Avatar asked Feb 01 '26 18:02

Remi.b


1 Answers

Unfortunately your problem can be reduced to subset-sum problem which is NP-Complete. Thus the exponential solution can't be avoided.

like image 109
sashas Avatar answered Feb 04 '26 10:02

sashas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!