Your problem. Bin packaging problem . Please find a pretty nice solution in the next article: Richard Corf's new algorithm for optimal bin packing (see an example of the problem there)
Let's see an example of an array:
MAXSIZE=20 [1 2 4 5 7 10 11]
Using the reference paper algorithm, you will receive:
[11 4 5] [10 7 2 1]
In short, this algorithm builds bin:
For example, in our case, the first step will be:
# Take max element [11] # We have 9 volume left # All smaller are [1 2 4 5 7] - greedy would take 7 in this case # 4 and 5 sums up to 9 which is best fit in this case so first bin become: [11 5 4] # Next step: take max [10] # we have 10 volume left. elements lower than 10: # [1 2 7] # this sums up to 10 in this case giving second bin [10 7 2 1]
And just one example of a greedy versus one:
ARR = [3, 3, 5, 5, 5, 5, 14] BINSIZE = 20 Greedy result: Size 3: [[14, 5], [5, 5, 5, 3], [3]] Mentioned alg result (size 2): [[14, 3, 3], [5, 5, 5, 5]]
You might also be interested in the Precise Algorithm section of the wiki page.