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
- Maximum possible difference of two subsets of an array
- k size subsets with maximum difference d between max and min
- Sum of maximum elements of all subsets
- Minimize the difference between minimum and maximum elements
- Maximum difference between group of k-elements and rest of the array.
- Find maximum difference between nearest left and right smaller elements
- 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
- Maximum difference between two elements such that larger element appears after the smaller number
- Maximize the difference between two subsets of a set with negatives
- Minimum difference between max and min of all K-size subsets
- Maximum and Minimum Product Subsets
- Minimum number of subsets with distinct elements
- Total number of subsets in which the product of the elements is even
- Find set of m-elements with difference of any two elements is divisible by k
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.