0

Given a set A containing n positive integers, how can I find the smallest integer >= 0 that can be obtained using all the elements in the set. Each element can be can be either added or subtracted to the total. Few examples to make this clear.

A = [ 2, 1, 3]

Result = 0 (2 + 1 - 3)

A = [1, 2, 0]

Result = 1 (-1 + 2 + 0)

A = [1, 2, 1, 7, 6]

Result = 1 (1 + 2 - 1 - 7 + 6)

BiGYaN
  • 6,974
  • 5
  • 30
  • 43
rohit89
  • 5,745
  • 2
  • 25
  • 42

1 Answers1

2

You can solve it by using Boolean Integer Programming. There are several algorithms (e.g. Gomory or branch and bound) and free libraries (e.g. LP-Solve) available.

Calculate the sum of the list and call it s. Double the numbers in the list. Say the doubled numbers are a,b,c. Then you have the following equation system:

Boolean x,y,z 

a*x+b*y+c*z >= s

Minimize ax+by+cz!

The boolean variables indicate if the corresponding number should be added (when true) or subtracted (when false).

[Edit]

I should mention that the transformed problem can be seen as "knapsack problem" as well:

Boolean x,y,z 

-a*x-b*y-c*z <= -s

Maximize ax+by+cz!
Landei
  • 54,104
  • 13
  • 100
  • 195