Minimize difference between maximum and minimum array elements by removing a K | C # program for the above approach ; Function to minimize difference between maximum and minimum array elements by removing a K - length subarray ; Size of array ; Stores the maximum and minimum in the suffix subarray [ i . . N - 1 ] ; Traverse the array ; Stores the maximum and minimum in the prefix subarray [ 0 . . i - 1 ] ; Store the minimum difference ; Traverse the array ; If the suffix doesn 't exceed  the end of the array ; Store the maximum element in array after removing subarray of size K ; Stores the maximum element in array after removing subarray of size K ; Update minimum difference ; Updating the maxPrefix and minPrefix with current element ; Print the minimum difference ; Driver Code
using System ; using System . Collections . Generic ; class GFg { static void minimiseDifference ( List < int > arr , int K ) { int N = arr . Count ; int [ ] maxSuffix = new int [ N + 1 ] ; int [ ] minSuffix = new int [ N + 1 ] ; maxSuffix [ N ] = - 1000000000 ; minSuffix [ N ] = 1000000000 ; maxSuffix [ N - 1 ] = arr [ N - 1 ] ; minSuffix [ N - 1 ] = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; -- i ) { maxSuffix [ i ] = Math . Max ( maxSuffix [ i + 1 ] , arr [ i ] ) ; minSuffix [ i ] = Math . Min ( minSuffix [ i + 1 ] , arr [ i ] ) ; } int maxPrefix = arr [ 0 ] ; int minPrefix = arr [ 0 ] ; int minDiff = maxSuffix [ K ] - minSuffix [ K ] ; for ( int i = 1 ; i < N ; ++ i ) { if ( i + K <= N ) { int maximum = Math . Max ( maxSuffix [ i + K ] , maxPrefix ) ; int minimum = Math . Min ( minSuffix [ i + K ] , minPrefix ) ; minDiff = Math . Min ( minDiff , maximum - minimum ) ; } maxPrefix = Math . Max ( maxPrefix , arr [ i ] ) ; minPrefix = Math . Min ( minPrefix , arr [ i ] ) ; } Console . WriteLine ( minDiff ) ; } public static void Main ( ) { List < int > arr = new List < int > ( ) { 4 , 5 , 8 , 9 , 1 , 2 } ; int K = 2 ; minimiseDifference ( arr , K ) ; } }