Algorithm to split an array into P subarrays of balanced sum

前端 未结 10 1888
面向向阳花
面向向阳花 2020-12-08 05:00

I have an big array of length N, let\'s say something like:

2 4 6 7 6 3 3 3 4 3 4 4 4 3 3 1

I need to split this array into P subarrays (in

10条回答
  •  悲&欢浪女
    2020-12-08 05:40

    I'm wondering whether the following would work:

    Go from the left, as soon as sum > sigma, branch into two, one including the value that pushes it over, and one that doesn't. Recursively process data to the right with rightSum = totalSum-leftSum and rightP = P-1.

    So, at the start, sum = 60

    2 4 6 7 6 3 3 3 4 3 4 4 4 3 3 1
    

    Then for 2 4 6 7, sum = 19 > sigma, so split into:

    2 4 6     7 6 3 3 3 4 3 4 4 4 3 3 1
    
    2 4 6 7     6 3 3 3 4 3 4 4 4 3 3 1
    

    Then we process 7 6 3 3 3 4 3 4 4 4 3 3 1 and 6 3 3 3 4 3 4 4 4 3 3 1 with P = 4-1 and sum = 60-12 and sum = 60-19 respectively.

    This results in, I think, O(P*n).

    It might be a problem when 1 or 2 values is by far the largest, but, for any value >= sigma, we can probably just put that in it's own partition (preprocessing the array to find these might be the best idea (and reduce sum appropriately)).

    If it works, it should hopefully minimise sum-of-squared-error (or close to that), which seems like the desired measure.

提交回复
热议问题