![]() |
VOOZH | about |
Given an array of non-negative integers of length N and an integer K. Partition the given array into two subsets of length K and N - K so that the difference between the sum of both subsets is maximum.
Examples :
Input : arr[] = {8, 4, 5, 2, 10}
k = 2
Output : 17
Explanation :
Here, we can make first subset of length k = {4, 2}
and second subset of length N - k = {8, 5, 10}. Then,
the max_difference = (8 + 5 + 10) - (4 + 2) = 17.
Input : arr[] = {1, 1, 1, 1, 1, 1, 1, 1}
k = 3
Output : 2
Explanation :
Here, subsets would be {1, 1, 1, 1, 1} and {1, 1, 1}.
So, max_difference would be 2
Choose k numbers with the largest possible sum. Then the solution obviously is k largest numbers. So that here greedy algorithm works - at each step we choose the largest possible number until we get all K numbers.
In this problem, we should divide the array of N numbers into two subsets of k and N - k numbers respectively. Consider two cases:
Now, Let's think about which of the two above cases actually gives the answer. We can easily see that a larger difference would be when more numbers are included in the group of largest numbers. Hence we could set M = max(k, N - k), find the sum of M largest numbers (let it be S1) and then the answer is S1 - (S - S1), where S is the sum of all numbers.
Below is the implementation of the above approach :
17
Time Complexity: O(N log N), to sort the array
Auxiliary Space: O(1), as no extra space is used
Further Optimizations : We can use Heap (or priority queue) to find M largest elements efficiently. Refer k largest(or smallest) elements in an array for details.