Given an array arr[] of positive integers of even length, the task is to partition these elements of arr[] into two groups each of odd length such that the absolute difference between the median of the two groups is minimized.
Examples:
Input: arr[] = { 1, 2, 3, 4, 5, 6 }
Output: 1
Explanation:
Group 1 can be [2, 4, 6] with median 4
Group 2 can be [1, 3, 5] with median 3.
The absolute difference between the two medians is 4 – 3 = 1, which can’t be minimized further with any kind of groupings formed.
Input: arr[] = { 15, 25, 35, 50 }
Output: 10
Explanation:
Group 1 can be [15, 25, 50] with median 25
Group 2 can be [35] with median 35.
The absolute difference between the two medians is 35 – 25 = 10, which can’t be minimized further with any kind of groupings formed.
Approach:
- If the given array arr[] is sorted, the middle elements of arr[] will give the minimum difference.
- So divide the arr[] in such a way that these two elements will be the median of two new arrays of odd length.
- Therefore, put the n/2th element of the arr[] in the first group and the (n/2 – 1)th element of the arr[] in the second group as a median respectively.
- Then abs(arr[n/2] – arr[(n/2)-1]) is the minimum difference between the two new arrays.
Below is the implementation of the above approach:
C++
#include "bits/stdc++.h"
using namespace std;
int minimizeMedian( int arr[], int n)
{
sort(arr, arr + n);
return abs (arr[n / 2] - arr[(n / 2) - 1]);
}
int main()
{
int arr[] = { 15, 25, 35, 50 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << minimizeMedian(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int minimiseMedian( int arr[], int n)
{
Arrays.sort(arr);
return Math.abs(arr[n / 2 ] - arr[(n / 2 ) - 1 ]);
}
public static void main (String[] args)
{
int arr[] = { 15 , 25 , 35 , 50 };
int n = arr.length;
System.out.println(minimiseMedian(arr, n));
}
}
|
Python3
def minimiseMedian(arr, n) :
arr.sort();
ans = abs (arr[n / / 2 ] - arr[(n / / 2 ) - 1 ]);
return ans;
if __name__ = = "__main__" :
arr = [ 15 , 25 , 35 , 50 ];
n = len (arr);
print (minimiseMedian(arr, n));
|
C#
using System;
class GFG
{
static int minimiseMedian( int []arr, int n)
{
Array.Sort(arr);
return Math.Abs(arr[n / 2] - arr[(n / 2) - 1]);
}
public static void Main(String[] args)
{
int []arr = { 15, 25, 35, 50 };
int n = arr.Length;
Console.WriteLine(minimiseMedian(arr, n));
}
}
|
Javascript
<script>
function minimiseMedian(arr, n) {
arr.sort((a, b) => a - b);
return Math.abs(arr[n / 2] - arr[(n / 2) - 1]);
}
let arr = [15, 25, 35, 50];
let n = arr.length;
document.write(minimiseMedian(arr, n));
</script>
|
Time Complexity: O(N*log N)
Auxiliary Space: O(1)