Number of K’s such that the given array can be divided into two sets satisfying the given conditions
Given an array arr[] of size N. The task is to find the number of K‘s such that the array can be divided into two sets containing equal number of elements if elements less than K are in one set and the rest of them are in the other set.
Note: N is always even.
Examples:
Input: arr[] = {9, 1, 4, 4, 6, 7}
Output: 2
{1, 4, 4} and {6, 7, 9} are the two sets.
K can be 5 or 6.
Input: arr[] = {1, 2, 3, 3, 4, 5}
Output: 0
Approach: An efficient approach is to sort the array. Then if two middle numbers are the same then the answer is zero otherwise answer is the difference between the two numbers.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int two_sets( int a[], int n)
{
sort(a, a + n);
return a[n / 2] - a[(n / 2) - 1];
}
int main()
{
int a[] = { 1, 4, 4, 6, 7, 9 };
int n = sizeof (a) / sizeof (a[0]);
cout << two_sets(a, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int two_sets( int a[], int n)
{
Arrays.sort(a);
return a[n / 2 ] - a[(n / 2 ) - 1 ];
}
public static void main(String []args)
{
int a[] = { 1 , 4 , 4 , 6 , 7 , 9 };
int n = a.length;
System.out.println(two_sets(a, n));
}
}
|
Python3
def two_sets(a, n) :
a.sort();
return (a[n / / 2 ] - a[(n / / 2 ) - 1 ]);
if __name__ = = "__main__" :
a = [ 1 , 4 , 4 , 6 , 7 , 9 ];
n = len (a);
print (two_sets(a, n));
|
C#
using System;
class GFG
{
static int two_sets( int []a, int n)
{
Array.Sort(a);
return a[n / 2] - a[(n / 2) - 1];
}
public static void Main(String []args)
{
int []a = { 1, 4, 4, 6, 7, 9 };
int n = a.Length;
Console.WriteLine(two_sets(a, n));
}
}
|
Javascript
<script>
function two_sets(a , n) {
a.sort();
return a[n / 2] - a[(n / 2) - 1];
}
var a = [ 1, 4, 4, 6, 7, 9 ];
var n = a.length;
document.write(two_sets(a, n));
</script>
|
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
Last Updated :
07 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...