Minimize difference between maximum and minimum of Array by at most K replacements | Function to find minimum difference between the maximum and the minimum elements arr [ ] by at most K replacements ; Check if turns are more than or equal to n - 1 then simply return zero ; Sort the array ; Set difference as the maximum possible difference ; Iterate over the array to track the minimum difference in k turns ; Return the answer ; Driver code ; Given array arr [ ] ; Given K replacements ; Function Call
def maxMinDifference ( arr , n , k ) : NEW_LINE INDENT if ( k >= n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT arr . sort ( ) NEW_LINE ans = arr [ n - 1 ] - arr [ 0 ] NEW_LINE i = k NEW_LINE j = n - 1 NEW_LINE while i >= 0 : NEW_LINE INDENT ans = min ( arr [ j ] - arr [ i ] , ans ) NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 6 , 11 , 15 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( maxMinDifference ( arr , N , K ) ) NEW_LINE DEDENT