VOOZH about

URL: https://www.geeksforgeeks.org/dsa/difference-maximum-sum-minimum-sum-n-m-elementsin-review/

⇱ Maximum difference between two subsets of m elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum difference between two subsets of m elements

Last Updated : 4 Mar, 2025

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).

[Naive Solution] - Using Sorting - O(n Log n) Time and O(1) Space

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.


Output
4

[Naive Solution] - Using Heap - O(n Log m) Time and O(m) Space

The idea is based on the solution discussed in k largest elements in an array

  • Create a Min Heap to Store m largest. We first push first m elements. For remaining n-m elements, we compare every element with the heap top. If Heap top is smaller, we insert the new element in the min heap
  • In the same way, create a Max Heap to Store m smallest.
  • Find the sums of elements in both the heaps and return the difference of two sums.

Output
4

Time Complexity: O(n * log m), this solution can work in O(m + (n-m) Log m) as build heap take linear time.

Comment
Article Tags: