Minimize difference between the largest and smallest array elements by K replacements | C # program for above approach ; Function to find minimum difference between the largest and smallest element after K replacements ; Create a MaxHeap ; Create a MinHeap ; Update maxHeap and MinHeap with highest and smallest K elements respectively ; Insert current element into the MaxHeap ; If maxHeap size exceeds K + 1 ; Remove top element ; Insert current element into the MaxHeap ; If maxHeap size exceeds K + 1 ; Remove top element ; Store all max element from maxHeap ; Store all min element from minHeap ; Generating all K + 1 possibilities ; Return answer ; Driver code ; Given array ; Function call
using System ; using System . Collections . Generic ; class GFG { static int minDiff ( int [ ] A , int K ) { if ( A . Length <= K + 1 ) return 0 ; List < int > maxHeap = new List < int > ( ) ; List < int > minHeap = new List < int > ( ) ; foreach ( int n in A ) { maxHeap . Add ( n ) ; maxHeap . Sort ( ) ; if ( maxHeap . Count > K + 1 ) maxHeap . RemoveAt ( 0 ) ; minHeap . Add ( n ) ; minHeap . Sort ( ) ; minHeap . Reverse ( ) ; if ( minHeap . Count > K + 1 ) minHeap . RemoveAt ( 0 ) ; } List < int > maxList = new List < int > ( ) ; while ( maxHeap . Count > 0 ) { maxList . Add ( maxHeap [ 0 ] ) ; maxHeap . RemoveAt ( 0 ) ; } List < int > minList = new List < int > ( ) ; while ( minHeap . Count > 0 ) { minList . Add ( minHeap [ 0 ] ) ; minHeap . RemoveAt ( 0 ) ; } int mindiff = Int32 . MaxValue ; for ( int i = 0 ; i < K ; i ++ ) { mindiff = Math . Min ( mindiff , maxList [ i ] - minList [ K - i ] ) ; } return mindiff ; } static void Main ( ) { int [ ] A = { - 1 , 3 , - 1 , 8 , 5 , 4 } ; int K = 3 ; Console . WriteLine ( minDiff ( A , K ) ) ; } }