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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimiseDifference ( vector < int > & arr , int K ) { int N = arr . size ( ) ; int maxSuffix [ N + 1 ] , minSuffix [ N + 1 ] ; maxSuffix [ N ] = -1e9 ; minSuffix [ N ] = 1e9 ; maxSuffix [ N - 1 ] = arr [ N - 1 ] ; minSuffix [ N - 1 ] = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; -- i ) { maxSuffix [ i ] = max ( maxSuffix [ i + 1 ] , arr [ i ] ) ; minSuffix [ i ] = 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 = max ( maxSuffix [ i + K ] , maxPrefix ) ; int minimum = min ( minSuffix [ i + K ] , minPrefix ) ; minDiff = min ( minDiff , maximum - minimum ) ; } maxPrefix = max ( maxPrefix , arr [ i ] ) ; minPrefix = min ( minPrefix , arr [ i ] ) ; } cout << minDiff << " STRNEWLINE " ; } int main ( ) { vector < int > arr = { 4 , 5 , 8 , 9 , 1 , 2 } ; int K = 2 ; minimiseDifference ( arr , K ) ; return 0 ; }