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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Sum of maximum elements of all subsets
- k size subsets with maximum difference d between max and min
- Maximum possible difference of two subsets of an array
- Divide array in two Subsets such that sum of square of sum of both subsets is maximum
- Maximum difference between two elements in an Array
- Minimize the difference between minimum and maximum elements
- Maximum length subarray with difference between adjacent elements as either 0 or 1
- Minimize the maximum difference between adjacent elements in an array
- Maximum absolute difference between distinct elements in an Array
- Check if maximum difference between indices of Non-Zero Elements is greater than X
- Minimize the maximum difference of adjacent elements after at most K insertions
- Maximum difference between group of k-elements and rest of the array.
- Maximum subsequence sum with adjacent elements having atleast K difference in index
- Find K elements whose absolute difference with median of array is maximum
- Find maximum number of elements such that their absolute difference is less than or equal to 1
- Choose k array elements such that difference of maximum and minimum is minimized
- Find maximum difference between nearest left and right smaller elements
- Count maximum elements of an array whose absolute difference does not exceed K
- Minimize the maximum absolute difference of adjacent elements in a circular array
- Maximum difference between two elements such that larger element appears after the smaller number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.