Find K elements whose absolute difference with 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
function findMedian ( a , n ) { if ( n % 2 != 0 ) return a [ Math . floor ( n / 2 ) ] ; return ( a [ Math . floor ( ( n - 1 ) / 2 ) ] + a [ Math . floor ( n / 2 ) ] ) / 2.0 ; } function kStrongest ( arr , n , k ) { arr . sort ( ) ; let median = findMedian ( arr , n ) ; let diff = Array . from ( { length : n } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < n ; i ++ ) { diff [ i ] = Math . abs ( median - arr [ i ] ) ; } let i = 0 , j = n - 1 ; while ( k > 0 ) { if ( diff [ i ] > diff [ j ] ) { document . write ( arr [ i ] + " " ) ; i ++ ; } else { document . write ( arr [ j ] + " " ) ; j -- ; } k -- ; } } let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let k = 3 ; let n = arr . length ; kStrongest ( arr , n , k ) ;