You are missing a complication.
Suppose that k
is even and n = 2.5*k
. Then half your groups are of size 2 and half of size 3. With a naïve approach, you have to consider the k choose 2 = O(2^k / sqrt(k))
possible ways to decide which are of size 2 and which are of size 3. This will take exponential time.
Let m
be the group size, rounded down. Then the optimal division of the first i
items into j
groups will be to have either m
elements in the last group and divide the first i-m
items into j-1
groups, or to have m+1
elements in the last group and divide the first i-m-1
items into j-1
groups. You can calculate that with a recursive function which returns a pair for (cost, linkedListOfChoices)
.
Add a caching layer to that recursion and it will run in polynomial time. This is called top-down dynamic programming.
Going from your optimal linkedListOfChoices
for dividing the whole list into k
groups to the actual groups should be straightforward. Here is an example.
Suppose we want to divide [0.1, 0.2, 0.4, 0.5, 0.6, 0.8, 0.9, 1.0, 2.1, 2.3]
into 4
groups. You should get a linked list corresponding to (but maybe with a very different representation):
[8, 9,
[5, 7,
[2, 4,
[0, 1,
null]]]]]
From which your groups (read inside out, turn indices back into numbers) are:
[[0.1, 0.2], [0.4, 0.5, 0.6], [0.8, 0.9, 1.0], [2.1, 2.3]]