Find K elements whose absolute difference with median of array is maximum | Java 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
import java . util . * ; 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 ) { Arrays . sort ( arr ) ; double median = findMedian ( arr , n ) ; int [ ] diff = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { diff [ i ] = ( int ) Math . abs ( median - arr [ i ] ) ; } int i = 0 , j = n - 1 ; while ( k > 0 ) { if ( diff [ i ] > diff [ j ] ) { System . out . print ( arr [ i ] + " ▁ " ) ; i ++ ; } else { System . out . print ( 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 ) ; } }