VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-difference-between-groups-of-size-two/

⇱ Minimum difference between groups of size two - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum difference between groups of size two

Last Updated : 17 Mar, 2025

Given an array of integers arr[] of the even size n. Form the groups of two elements each from the given array arr[], such that the difference between the group with highest sum and the group with lowest sum is minimum. Your task is to find the minimum possible difference.

Note: An element can be a part of only one group, and all the elements need to be part of some group.

Example:

Input: arr[] = [ 2, 6, 4, 3 ]
Output: 1
Explanation: The two groups can be [2, 6] and [4, 7] with different between their sum of elements = 2 + 6 - 4 + 3 = 1, which is the minimum possible.

Input: arr[] = [ 11, 4, 3, 5, 7, 1 ]
Output: 3
Explanation: The one possible combination of groups are [11, 1], [3, 7] and [4, 5], with the sum of their elements 12, 10, and 9 respectively.

[Naive Approach] - Using Sorting - O(n^3) Time

A simple approach would be to try all combinations of array elements and check against each set of combination and difference between the-group-with-the-highest-sum and the one with-the-lowest-sum. A total of n*(n-1)/2 such groups would be formed (nC2). 

[Expected Approach] - Using Sorting - O(n * log n) Time and O(n) Space

It can be observed that the difference between sum of groups of elements will be smallest if the largest element is paired with the smallest one, and similarly the second largest element is paired up with the second smallest element.
The idea is to sort the given array arr[], group the first element with the last element, and the second element with the second last element and so on. Store the sum of these groups in an auxiliary array. Thereafter, find the highest and lowest sum, the difference between two is the required answer.

Below is given the implementation:


Output
1

[Optimized Approach] - Using Sorting - O(n * log n) Time and O(1) Space

In the above approach, instead of storing the sum of groups of elements, the idea is to directly compute the highest and lowest sum as we only need these two values. And after grouping all the elements, return the difference of the highest and lowest sum.

Below is given the implementation:


Output
1
Comment
Article Tags:
Article Tags: