Minimize difference between the largest and smallest array elements by K replacements | C ++ program for the above approach ; Function to find minimum difference between largest and smallest element after K replacements ; Sort array in ascending order ; Minimum difference ; Check for all K + 1 possibilities ; Return answer ; Driver Code ; Given array ; Length of array ; Prints the minimum possible difference
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDiff ( int A [ ] , int K , int n ) { sort ( A , A + n ) ; if ( n <= K ) return 0 ; int mindiff = A [ n - 1 ] - A [ 0 ] ; if ( K == 0 ) return mindiff ; for ( int i = 0 , j = n - 1 - K ; j < n ; ) { mindiff = min ( mindiff , A [ j ] - A [ i ] ) ; i ++ ; j ++ ; } return mindiff ; } int main ( ) { int A [ ] = { -1 , 3 , -1 , 8 , 5 , 4 } ; int K = 3 ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minDiff ( A , K , n ) ; return 0 ; }