Minimize difference between maximum and minimum array elements by exactly K removals | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void minimumRange ( int arr [ ] , int N , int K ) { if ( K >= N ) { cout << 0 ; return ; } sort ( arr , arr + N ) ; int left = 0 , right = N - 1 , i ; for ( i = 0 ; i < K ; i ++ ) { if ( arr [ right - 1 ] - arr [ left ] < arr [ right ] - arr [ left + 1 ] ) right -- ; else left ++ ; } cout << arr [ right ] - arr [ left ] ; } int main ( ) { int arr [ ] = { 5 , 10 , 12 , 14 , 21 , 54 , 61 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 4 ; minimumRange ( arr , N , K ) ; return 0 ; }