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

前端 未结 1 2041
面向向阳花
面向向阳花 2021-01-03 02:21

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 chan

相关标签:
1条回答
  • 2021-01-03 02:45

    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.

    0 讨论(0)
提交回复
热议问题