Given an array of n integers. We are allowed to add k additional integer in the array and then find the median of the resultant array. We can choose any k values to be added.
Constraints:
k < n
n + k is always odd.
Examples :
Input : arr[] = { 4, 7 }
k = 1
Output : 7
Explanation : One of the possible solutions
is to add 8 making the array [4, 7, 8], whose
median is 7
Input : arr[] = { 6, 1, 1, 1, 1 }
k = 2
Output : 1
Explanation : No matter what elements we add
to this array, the median will always be 1
We first sort the array in increasing order. Since value of k is less than n and n+k is always odd, we can always choose to add k elements that are greater than the largest element of an array, and (n+k)/2th element is always a median of the array.
C++
#include <bits/stdc++.h>
using namespace std;
void printMedian( int arr[], int n, int K)
{
sort(arr, arr + n);
cout << arr[(n + K) / 2];
}
int main()
{
int arr[] = { 5, 3, 2, 8 };
int k = 3;
int n = sizeof (arr) / sizeof (arr[0]);
printMedian(arr, n, k);
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static void printMedian( int arr[], int n, int K)
{
Arrays.sort(arr);
System.out.print(arr[(n + K) / 2 ]);
}
public static void main (String[] args)
{
int arr[] = { 5 , 3 , 2 , 8 };
int k = 3 ;
int n = arr.length;
printMedian(arr, n, k);
}
}
|
Python3
def printMedian (arr, n, K):
arr.sort()
print ( arr[ int ((n + K) / 2 )])
arr = [ 5 , 3 , 2 , 8 ]
k = 3
n = len (arr)
printMedian(arr, n, k)
|
C#
using System;
class GFG
{
static void printMedian( int []arr, int n, int K)
{
Array.Sort(arr);
Console.Write(arr[(n + K) / 2]);
}
public static void Main ()
{
int []arr = { 5, 3, 2, 8 };
int k = 3;
int n = arr.Length;
printMedian(arr, n, k);
}
}
|
PHP
<?php
function printMedian( $arr , $n , $K )
{
sort( $arr );
echo $arr [( $n + $K ) / 2];
}
$arr = array ( 5, 3, 2, 8 );
$k = 3;
$n = count ( $arr );
printMedian( $arr , $n , $k );
?>
|
Javascript
<script>
function printMedian(arr, n, K)
{
arr.sort();
document.write(arr[(Math.floor((n + K) / 2))]);
}
let arr = [ 5, 3, 2, 8 ];
let k = 3;
let n = arr.length;
printMedian(arr, n, k);
</script>
|
Output :
8
Time complexity: O(nlog(n))
Auxiliary Space: O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!