You have a set of items and that form a subset whose sum is less than X
, so that it has the largest possible sum and has the largest possible number of items.
This problem is quite similar to knapsack problem:
The backpack problem (in English, Knapsack problem) is a combinatorial optimization problem. The name is given due to the model of a situation where it is necessary to fill a backpack with objects of different weights and values. The goal is to fill the backpack with the highest possible value, not exceeding the maximum weight.
The difference is that in your case weight and value are the same thing. You have a value limit, but you want to maximize value. This problem is NP-Complete, that is: there is no known solution to calculate the optimal solution in non-exportive time.
A simple solution is to use the following recursive algorithm:
# Encontre o maior conjunto com os n primeiros itens de set tal que seja menor que o limit
def bestsubset(set, n, limit)
if n == 0
# O melhor conjunto com zero itens é o conjunto vazio
return []
end
if set[n-1] > limit
# Se o ultimo for menor que o limite, exclua ele
return bestsubset(set, n-1, limit)
end
# a = melhor conjunto excluindo o ultimo item
# b = melhor conjunto incluindo o ultimo item
a = bestsubset(set, n-1, limit)
b = bestsubset(set, n-1, limit-set[n-1]) + [set[n-1]]
# computar as somas
sum_a = a.reduce(:+) || 0
sum_b = b.reduce(:+) || 0
if sum_a > sum_b
return a
else
# se soma deu igual, retorna o que tem mais itens
return b
end
end
.
p bestsubset([3,1,1,1,2,7], 6, 5) #=> [1, 1, 1, 2]
I wrote in Ruby, but you can adapt to any language.
The best possible solution would be just a combination closer to 20D or tb matter the amount of items? Type, 4 items that add up to 18D is a better solution than 3 items that add up to 18D?
– CCastro
Never mind the number of items.. Excuse Castro. In the case of 4 to 3. the first option "4 to 18D" is the best solution.
– Larïssa Moura
sounds a lot like that question. Help you? http://answall.com/q/7075/1271
– Marcos Banik
Marcos, I don’t need a distribution between n-lists. I need the set of the first group to be the best choice of items to reach the limit value.
– Larïssa Moura
To get an idea, I thought of the following solution: Form all possible sets for the elements - provided that the sum does not exceed the value - and select the group that gets the largest sum. But this approach has been very costly. Even more so because it is not possible to determine the number of sets at first.
– Larïssa Moura