Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select combination of elements from array whose sum is smallest possible positive number

Suppose I have an array of M elements, all numbers, negative or positive or zero.

Can anyone suggest an algorithm to select N elements from the array, such that the sum of these N elements is the smallest possible positive number?

Take this array for example:

-1000,-700,-400,-200,-100,-50,10,100,300,600,800,1200

Now I have to select any 5 elements such that their sum is the smallest possible positive number.

like image 703
Shubham Gupta Avatar asked Jun 27 '13 17:06

Shubham Gupta


People also ask

What is combination of sum problem?

Given an array of positive integers arr[] and an integer x, The task is to find all unique combinations in arr[] where the sum is equal to x. The same repeated number may be chosen from arr[] an unlimited number of times.

How do you find the minimum sum of an array?

Minimum sum = (sumOfArr - subSum) + (subSum/ X) where sumOfArr is the sum of all elements of the array and subSum is the maximum sum of the subarray.

How do I find the minimum elements in the array which has a sum equal to the given value?

Approach: The idea is to find every possible sequence recursively such that their sum is equal to the given S and also keep track of the minimum sequence such that their sum is given S. In this way, the minimum possible solution can be calculated easily.

How do you find the smallest positive integer?

So, we omit all the negative integers and zero from the set of integers, and we are left with the set {1, 2, 3, …}. The smallest of the numbers in the set {1, 2, 3, …} is 1. So, the number 1 is the smallest positive integer. So positive means Hence is the smallest.


1 Answers

Formulation

For i = 1, ..., M:

  • Let a_i be the ith number in your list of candidates
  • Let x_i denote whether the ith number is included in your set of N chosen numbers

Then you want to solve the following integer programming problem.

minimize: sum(a_i * x_i)
with respect to: x_i
subject to:
    (1) sum(a_i * x_i) >= 0
    (2) sum(x_i) = N
    (3) x_i in {0, 1}

You can apply an integer program solver "out of the box" to this problem to find the optimal solution or a suboptimal solution with controllable precision.

Resources

  • Integer programming
  • Explanation of branch-and-bound integer program solver
like image 163
Timothy Shields Avatar answered Sep 29 '22 04:09

Timothy Shields