![]() |
VOOZH | about |
Given an array of n integers and a number m, find the maximum possible difference between two sets of m elements chosen from given array.
Examples:
Input : arr[] = 1 2 3 4 5
m = 4
Output : 4
The maximum four elements are 2, 3, 4 and 5. The minimum four elements are 1, 2, 3 and 4. The difference between two sums is (2 + 3 + 4 + 5) - (1 + 2 + 3 + 4) = 4
Input : arr[] = 5 8 11 40 15
m = 2
Output : 42
The difference is (40 + 15) - (5 + 8).
The idea is to first sort the array, then find sum of first m elements and sum of last m elements. Finally return difference between two sums.
4
The idea is based on the solution discussed in k largest elements in an array
4
Time Complexity: O(n * log m), this solution can work in O(m + (n-m) Log m) as build heap take linear time.