Let packets
contain the source packets.
The division of k
into the sums p = 1, 2, ..., m
numbers >= 1
and < k
(there are such O(2^k)
such sections). For each section, iterating over packets
and add those numbers, the rest modulo k
is one of the elements in the section, and then remove this element from the section. Keep the minimum amount and update the global minimum. Note that if m > p
, you must also have m - p
zeros.
You might think that this is O(2^k * n)
and it is too slow, but in fact you do not need to iterate over the packets
array for each section if you save num[i] = how many numbers have packets[i] % k == i
, in which case it becomes O(2^k + n)
. To cope with the minimum amount requirement, you can save num[i] = the list of the numbers that have packets[i] % k == i
, which allows you to always select the smallest numbers for a valid section.
Ivlad source share