Given a fixed number of infinite-capacity containers and a list of items of varying weights, how can I best place the items into the containers preserving their original order in a way that minimises the difference between the heaviest and lightest containers?
For example, given 3 containers and 10 items with weights [19, 7, 12, 1, 9, 11, 3, 17, 10, 8] the optimal solution is:
- 19, 7
- 12, 1, 9, 11, 3
- 17, 10, 8
Such that the difference between the heaviest and lightest containers is (12 + 1 + 9 + 11 + 3) - (19 + 7) = 10.
My current algorithm is to:
- calculate the target bin weight as the sum of all item weights divided by the number of containers
- if adding the next item to the active container would bring its weight closer to the target then add it to the active container
- otherwise move to the next container and add the item
- repeat until all items have been placed in containers
This algorithm works well for lists of items of similar weights but doesn't find the best solution when there are one or more very heavy items.
For example, with 4 containers and item weights [3, 8, 2, 4, 8, 2, 27, 20] the above algorithm gives:
- 3, 8, 2, 4
- 8, 2
- 27
- 20
With a weight range of 27 - (8 + 2) = 17.
However the optimal solution is in fact:
- 3, 8, 2
- 4, 8, 2
- 27
- 20
With a weight range of 27 - (3 + 8 + 2) = 14.
How can I find the optimal solution?