Minimize difference between maximum and minimum array elements by removing a K | 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
def minimiseDifference ( arr , K ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE maxSuffix = [ 0 for i in range ( N + 1 ) ] NEW_LINE minSuffix = [ 0 for i in range ( N + 1 ) ] NEW_LINE maxSuffix [ N ] = - 1e9 NEW_LINE minSuffix [ N ] = 1e9 NEW_LINE maxSuffix [ N - 1 ] = arr [ N - 1 ] NEW_LINE minSuffix [ N - 1 ] = arr [ N - 1 ] NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT maxSuffix [ i ] = max ( maxSuffix [ i + 1 ] , arr [ i ] ) NEW_LINE minSuffix [ i ] = min ( minSuffix [ i + 1 ] , arr [ i ] ) NEW_LINE i -= 1 NEW_LINE DEDENT maxPrefix = arr [ 0 ] NEW_LINE minPrefix = arr [ 0 ] NEW_LINE minDiff = maxSuffix [ K ] - minSuffix [ K ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( i + K <= N ) : NEW_LINE INDENT maximum = max ( maxSuffix [ i + K ] , maxPrefix ) NEW_LINE minimum = min ( minSuffix [ i + K ] , minPrefix ) NEW_LINE minDiff = min ( minDiff , maximum - minimum ) NEW_LINE DEDENT maxPrefix = max ( maxPrefix , arr [ i ] ) NEW_LINE minPrefix = min ( minPrefix , arr [ i ] ) NEW_LINE DEDENT print ( minDiff ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 5 , 8 , 9 , 1 , 2 ] NEW_LINE K = 2 NEW_LINE minimiseDifference ( arr , K ) NEW_LINE DEDENT