Algorithm to split an array into P subarrays of balanced sum

前端 未结 10 1849
面向向阳花
面向向阳花 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:58

    @Gumbo 's answer is clear and actionable, but consumes lots of time when length(A) bigger than 400 and P bigger than 8. This is because that algorithm is kind of brute-forcing with benefits as he said.

    In fact, a very fast solution is using dynamic programming.

    Given an array A of positive integers and a positive integer P, separate the array A into P non-overlapping subarrays such that the difference between the sum of each subarray and the perfect sum of the subarrays (sum(A)/P) is minimal.

    Measure: , where is sum of elements of subarray , is the average of P subarray' sums.

    This can make sure the balance of sum, because it use the definition of Standard Deviation.

    Persuming that array A has N elements; Q(i,j) means the minimum Measure value when split the last i elements of A into j subarrays. D(i,j) means (sum(B)-sum(A)/P)^2 when array B consists of the i~jth elements of A ( 0<=i<=j ).

    The minimum measure of the question is to calculate Q(N,P). And we find that:

    Q(N,P)=MIN{Q(N-1,P-1)+D(0,0); Q(N-2,P-1)+D(0,1); ...; Q(N-1,P-1)+D(0,N-P)}
    

    So it like can be solved by dynamic programming.

     Q(i,1) = D(N-i,N-1)
    
     Q(i,j) = MIN{ Q(i-1,j-1)+D(N-i,N-i); 
                   Q(i-2,j-1)+D(N-i,N-i+1); 
                   ...; 
                   Q(j-1,j-1)+D(N-i,N-j)}
    

    So the algorithm step is:

     1. Cal j=1:
    
        Q(1,1), Q(2,1)... Q(3,1)
    
     2. Cal j=2:
    
        Q(2,2) = MIN{Q(1,1)+D(N-2,N-2)};
    
        Q(3,2) = MIN{Q(2,1)+D(N-3,N-3); Q(1,1)+D(N-3,N-2)}
    
        Q(4,2) = MIN{Q(3,1)+D(N-4,N-4); Q(2,1)+D(N-4,N-3); Q(1,1)+D(N-4,N-2)}
    
     ... Cal j=...
    
     P. Cal j=P:
    
        Q(P,P), Q(P+1,P)...Q(N,P)
    
    The final minimum Measure value is stored as Q(N,P)! 
    To trace each subarray's length, you can store the 
    MIN choice when calculate Q(i,j)=MIN{Q+D...}
    

    space for D(i,j);

    time for calculate Q(N,P)

    compared to the pure brute-forcing algorithm consumes time.

提交回复
热议问题