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
using System ; class GFG { static 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 ; } static void kStrongest ( int [ ] arr , int n , int k ) { Array . Sort ( arr ) ; int i = 0 ; double median = findMedian ( arr , n ) ; int [ ] diff = new int [ n ] ; for ( i = 0 ; i < n ; i ++ ) { diff [ i ] = ( int ) Math . Abs ( median - arr [ i ] ) ; } int j = n - 1 ; i = 0 ; while ( k > 0 ) { if ( diff [ i ] > diff [ j ] ) { Console . Write ( arr [ i ] + " ▁ " ) ; i ++ ; } else { Console . Write ( arr [ j ] + " ▁ " ) ; j -- ; } k -- ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int k = 3 ; int n = arr . Length ; kStrongest ( arr , n , k ) ; } }