Minimize difference between maximum and minimum of Array by at most K replacements | C ++ program of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxMinDifference ( int arr [ ] , int n , int k ) { if ( k >= n - 1 ) return 0 ; sort ( arr , arr + n ) ; int ans = arr [ n - 1 ] - arr [ 0 ] ; for ( int i = k , j = n - 1 ; i >= 0 ; -- i , -- j ) { ans = min ( arr [ j ] - arr [ i ] , ans ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 4 , 6 , 11 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << maxMinDifference ( arr , N , K ) ; return 0 ; }