Minimize difference between maximum and minimum array elements by exactly K removals | Function to minimize the difference of the maximum and minimum array elements by removing K elements ; Base Condition ; Sort the array ; Initialize left and right pointers ; Iterate for K times ; Removing right element to reduce the difference ; Removing the left element to reduce the difference ; Print the minimum difference ; Driver Code ; Function Call
def minimumRange ( arr , N , K ) : NEW_LINE INDENT if ( K >= N ) : NEW_LINE INDENT print ( 0 , end = ' ' ) ; NEW_LINE return ; NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE left = 0 ; right = N - 1 ; NEW_LINE for i in range ( K ) : NEW_LINE INDENT if ( arr [ right - 1 ] - arr [ left ] < arr [ right ] - arr [ left + 1 ] ) : NEW_LINE INDENT right -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT left += 1 ; NEW_LINE DEDENT DEDENT print ( arr [ right ] - arr [ left ] , end = ' ' ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 10 , 12 , 14 , 21 , 54 , 61 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 4 ; NEW_LINE minimumRange ( arr , N , K ) ; NEW_LINE DEDENT