1

I have an array of n positive numbers. I need to split it into N contiguous sub-arrays; n > N.

I need to minimize [max S(j) over j] - [min S(j) over j], where S(j) denotes sum of elements in j-th sub-array, (j = 1,...,N).

I.e., all sub-arrays should have "same" sum of elements.

I am sure this problem is known.. Could someone point me to algorithms, implementations, or publications?

user2052436
  • 4,321
  • 1
  • 25
  • 46

2 Answers2

1

This problem is equivalent to finding the min of max S(j) over all j.

Intuition:

  • Assume that the minimum of all possible max S(j) over all j is xmax, so the result will be xmax - xmin.

  • Assume that, another ymax > xmax that could provide us a better result, which means ymax - ymin < xmax - xmin -> ymin > xmin -> min S(j) - ymax > min S(j) - xmax, which should not happen.

So, the problem point down to finding the min of max S(j) over all j

This can be solved by using binary search. Assuming that the total sum of the whole array is X, so we have our algo:

int start = 0;
int end = X;
int result = 0;
while(start <= end){
    int mid = (start + end)/2;
    for(int i = 0; i < n; i++){
       if sum of current segment > mid
           split

    }
    if total segment > N
       start = mid + 1;
    else 
       update result;
       end = mid - 1;
}
Pham Trung
  • 11,204
  • 2
  • 24
  • 43
  • I disagree. Consider split of `[10 7 3 4]` into 3 sub-arrays. Looking for `min` of `max` gives 2 equivalent answers: `10 | 7 3 | 4` and `10 | 7 | 3 4`. Looking for `min` of `max - min` gives only one best answer: `10 | 7 | 3 4` – user2052436 Nov 20 '18 at 15:39
0

Find the sum of the whole array and call that T, and do k = T / N to determine the ideal sum of the first sub-array's elements. Then create the first sub-array linearly (starting from the start of the array) while trying to minimise the difference between k and sum of all values in the sub-array so far + potential next element when deciding if the sub-array should/shouldn't include the next element.

Then use recursion to split the remaining part of the array into N-1 pieces, stopping when N == 1 (the remaining part of the array is the last sub-array).

Note: This doesn't give the optimal solution in all cases, but it is relatively fast and for the purpose of (dynamic) load balancing there's a risk that loads will change so often that anything more expensive (that does always find the optimal solution) is pointless.

Brendan
  • 35,656
  • 2
  • 39
  • 66