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
using System ; class GFG { static void minimumRange ( int [ ] arr , int N , int K ) { if ( K >= N ) { Console . Write ( 0 ) ; return ; } Array . Sort ( arr ) ; 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 ++ ; } Console . Write ( arr [ right ] - arr [ left ] ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 5 , 10 , 12 , 14 , 21 , 54 , 61 } ; int N = arr . Length ; int K = 4 ; minimumRange ( arr , N , K ) ; } }