Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm splitting array into sub arrays where the maximum sum among all sub arrays is as low as possible

Let's say we have an array of ints: a = {2,4,3,5}

And we have k = 3.

We can split array a in k (3) sub arrays in which the order of the array cannot be changed. The sum of each sub array has to be as low as possible so that the maximum sum among all sub arrays is as low as possible.

For the above solution this would give {2, 4}, {3}, {5} which has a maximum sum of 6 (4 + 2).

A wrong answer would be {2}, {4, 3}, {5}, because the maximum sum is 7 (4 + 3) in this case.

I've tried creating a greedy algorithm which calculates the average of the entire array by summing all ints and dividing it by the resulting amount of sub arrays. So in the example above this would mean 14 / 3 = 4 (integer division). It will then add up numbers to a counter as long as it's < than the average number. It will then recalculate for the rest of the sub array.

My solution gives a good approximation and can be used as heuristic, but will not always give me the right answer.

Can someone help me out with an algorithm which gives me the optimal solution for all cases and is better than O(N²)? I'm looking for an algorithm which is O(n log n) approximately.

Thanks in advance!

like image 367
Robinhopok Avatar asked Mar 18 '16 03:03

Robinhopok


1 Answers

We can use binary search to solve this problem.

So, assume that the maximum value for all sub-array is x, so, we can greedily choose each sub-array in O(n) so that the sum of each subarray is maximum and less than or equals to x. After creating all subarray, if the number of sub-array is less than or equal to k, so x is one possible solution, or else, we increase x.

Pseudocode:

int start = Max_Value_In_Array;
int end = Max_Number;

while(start <= end)
   int mid = (start + end)/2;
   int subSum = 0;
   int numberOfSubArray = 1;
   for(int i = 0; i < n; i++){
      if(subSum + data[i] > mid){
          subSum = data[i];
          numberOfSubArray++;
      }else{
          subSum += data[i];
      }
   }
   if(numberOfSubArray <= k)
       end = mid - 1;
   else
       start = mid + 1;

Time complexity O(n log k) with k is the maximum sum possible.

like image 152
Pham Trung Avatar answered Nov 20 '22 08:11

Pham Trung