![]() |
VOOZH | about |
You are given an array arr[] containing N positive integers. Your task is to divide the array into K subarrays so that the maximum sum in a subarray is as small as possible.
Examples:
Input: N = 5, K = 3, arr[] = {2, 4, 7, 3, 5}
Output: 8
Explanation: The 3 subarrays are: {2, 4}, {7} and {3, 5} with sum of 6, 7 and 8 respectively.Input: N = 4, K = 2, arr = {3, 3, 2, 2}
Output: 6
Explanation: The 2 subarrays are: {3, 3} and {2, 2} with sum of 6 and 4 respectively.
Approach: To solve the problem, follow the below idea:
Let's assume the minimum of maximum sum of all subarrays to be X. So, for every sum S < X, we know that it is impossible to partition the whole array arr[] into K subarrays such that the sum of each subarray <= S. Also for every sum S >= X, we know that it is always possible to partition the whole array arr[] into K subarrays such that the sum of each subarray <= S. Now, the problem is to find the value of X.
We can find the value of X using Binary Search. If we observe carefully, the minimum possible answer will always be greater than or equal to the maximum element in the array. Also, the maximum possible will always be less than or equal to sum of all elements in the array. Now, we can binary search with low = maximum element in the array and high = total sum of arr[].
We can calculate mid value, and check if we can partition the whole array arr[] into K subarrays such that the sum of each subarray <= mid. If yes, then we can update ans to mid and then reduce our search space by moving high to mid - 1. Else if it is impossible to partition the array arr[] into K subarrays with sum <= mid, then we only reduce our search space by moving low to mid + 1.
We can continue reducing the search space till low <= high, after which we return ans.
Step-by-step algorithm:
Below is the implementation of the algorithm:
8
Time Complexity: O(N * logN), where N is the difference between the sum of all elements and the maximum element in the array.
Auxiliary Space: O(1)