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
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.