Find K elements whose absolute difference with median of array is maximum | C ++ implementation to find first K elements whose difference with the median of array is maximum ; Function for calculating median ; check for even case ; Function to find the K maximum absolute difference with the median of the array ; Sort the array . ; Store median ; Find and store difference ; If diff [ i ] is greater print it Else print diff [ j ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double findMedian ( int a [ ] , int n ) { if ( n % 2 != 0 ) return ( double ) a [ n / 2 ] ; return ( double ) ( a [ ( n - 1 ) / 2 ] + a [ n / 2 ] ) / 2.0 ; } void kStrongest ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; double median = findMedian ( arr , n ) ; int diff [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { diff [ i ] = abs ( median - arr [ i ] ) ; } int i = 0 , j = n - 1 ; while ( k > 0 ) { if ( diff [ i ] > diff [ j ] ) { cout << arr [ i ] << " ▁ " ; i ++ ; } else { cout << arr [ j ] << " ▁ " ; j -- ; } k -- ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; kStrongest ( arr , n , k ) ; return 0 ; }