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
def findMedian ( a , n ) : NEW_LINE INDENT if ( n % 2 != 0 ) : NEW_LINE INDENT return a [ int ( n / 2 ) ] NEW_LINE DEDENT return ( a [ int ( ( n - 1 ) / 2 ) ] + a [ int ( n / 2 ) ] ) / 2.0 NEW_LINE DEDENT def kStrongest ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE median = findMedian ( arr , n ) NEW_LINE diff = [ 0 ] * ( n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT diff [ i ] = abs ( median - arr [ i ] ) NEW_LINE DEDENT i = 0 NEW_LINE j = n - 1 NEW_LINE while ( k > 0 ) : NEW_LINE INDENT if ( diff [ i ] > diff [ j ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ j ] , end = " ▁ " ) NEW_LINE j -= 1 NEW_LINE DEDENT k -= 1 NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE k = 3 NEW_LINE n = len ( arr ) NEW_LINE kStrongest ( arr , n , k ) NEW_LINE