![]() |
VOOZH | about |
Given an array arr[], and an integer N. The task is to maximize the sum of minimum and maximum of each group in a distribution of the array elements in N groups where the size of each group is given in an array b[] of size N.
Examples:
Input: a[] = {17, 12, 11, 9, 8, 8, 5, 4, 3}, N = 3,
b[] = {2, 3, 4}
Output: 60
Explanation: The array elements should be distributed in groups {17, 9} {12, 8, 8} {11, 5, 4, 3}.
So the sum becomes (17 + 9) + (12 + 8) + (11 + 3) = 26 + 20 + 14 = 60Input: a[] = {12, 3, 4, 2, 5, 9, 8, 1, 2}, N = 3,
b[] = {1, 4, 4}
Output: 45
Approach: This problem can be solved by using the Greedy Approach and some implementation. Follow the steps below to solve the given problem.
See the illustration below for better understanding.
Illustration:
Consider an example: arr[] = {17, 12, 11, 9, 8, 8, 5, 4, 3}, N = 3 and b[] = {2, 3, 4}
Firstly, sort array arr[] in descending order and b[] in ascending order, After then put the first N greatest element of array arr[] to each group as shown in fig.
👁 Image
Secondly, Fill each group with the rest of the element of array arr[] (one group at a time)
👁 Image
Therefore answer will contain the sum of the first N elements of array arr[] i.e. 17, 12, 11 and also the last element which is filled in each group i.e. 9, 8 and 3.
Below is the implementation of the above approach.
60
Time complexity: O(M * logM) where M is the size of array arr.
Auxiliary Space: O(1)