Minimize the number of groups where the sum of the elements of the group is below a certain value

Let's say I have a list of 10 elements and max_sum:

items = [1, 2, 4, 4, 10, 10, 15, 18, 21, 22]
max_sum = 30

I want to group the elements in items, and I want to find the minimum number of groups, provided that the sum of the elements in each group is less than the specified value max_sum, where all the elements are itemsless max_sum.

The general idea of ​​the algorithm:

  • initialize 1) empty list new_group, 2) float space_leftin group=(max_sum - sum(new_group))
  • find the largest item like item <= space_left
  • add the largest item to new_group
  • update space_left
  • remove item from items
  • once min(items)> space_left, start over
  • count cycles to find the minimum number of groups

So, for given values, this algorithm will give 4 groups:

[22, 4, 4]
[21, 2, 1]
[18, 10]
[15, 10]

, , , / . !

+4
1

. , . :.

 items = [13, 11, 10, 10, 9, 7]
 max_sum = 30

 First group  => [13, 11] (leaving a diff of 6)
 Second group => [10, 10, 9] (leaving a diff of 1)
 Third group  => [7]

First group  => [13, 10, 7]
Second group => [11, 10, 9]

, . , Wikipedia , .

+3

Source: https://habr.com/ru/post/1675577/


All Articles