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.
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.
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.
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.
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.
For i = 1, ..., M
:
a_i
be the i
th number in your list of candidatesx_i
denote whether the i
th number is included in your set of N
chosen numbersThen 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With