Minimize difference between the largest and smallest array elements by K replacements | Function to find minimum difference between largest and smallest element after K replacements ; Sort array in ascending order ; Length of array ; Minimum difference ; Check for all K + 1 possibilities ; Return answer ; Driver Code ; Given array ; Prints the minimum possible difference
def minDiff ( A , K ) : NEW_LINE INDENT A . sort ( ) ; NEW_LINE n = len ( A ) ; NEW_LINE if ( n <= K ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT mindiff = A [ n - 1 ] - A [ 0 ] ; NEW_LINE if ( K == 0 ) : NEW_LINE INDENT return mindiff ; NEW_LINE DEDENT i = 0 ; NEW_LINE for j in range ( n - 1 - K , n ) : NEW_LINE INDENT mindiff = min ( mindiff , A [ j ] - A [ i ] ) ; NEW_LINE i += 1 ; NEW_LINE j += 1 ; NEW_LINE DEDENT return mindiff ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ - 1 , 3 , - 1 , 8 , 5 , 4 ] ; NEW_LINE K = 3 ; NEW_LINE print ( minDiff ( A , K ) ) ; NEW_LINE DEDENT