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.
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.
We can optimize the above solution using more efficient approaches discussed in below post.
k largest(or smallest) elements in an array | added Min Heap method
- Height of a complete binary tree (or Heap) with N nodes
- Heap Sort for decreasing order using min heap
- Print uncommon elements from two sorted arrays
- Maximum sum of increasing order elements from n arrays
- Pairs such that one is a power multiple of other
- Inverse Permutation
- Maximum distinct elements after removing k elements
- Minimum product of k integers in an array of positive Integers
- K-th Largest Sum Contiguous Subarray
- Print all nodes less than a value x in a Min Heap.
- Median of Stream of Running Integers using STL
- Largest triplet product in a stream
- Find k numbers with most occurrences in the given array
- K'th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)
- k largest(or smallest) elements in an array | added Min Heap method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.