Minimize difference between the largest and smallest array elements by K replacements | 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 ; Given array ; Function call
function minDiff ( A , K , N ) { if ( N <= K + 1 ) return 0 ; var maxHeap = [ ] ; var minHeap = [ ] ; for ( var i = 0 ; i < N ; i ++ ) { maxHeap . push ( A [ i ] ) ; maxHeap . sort ( ( a , b ) => b - a ) ; if ( maxHeap . length > K + 1 ) maxHeap . pop ( ) ; minHeap . push ( A [ i ] ) ; minHeap . sort ( ( a , b ) => a - b ) ; if ( minHeap . length > K + 1 ) minHeap . pop ( ) ; } var maxList = [ ] ; while ( maxHeap . length > 0 ) { maxList . push ( maxHeap [ maxHeap . length - 1 ] ) ; maxHeap . pop ( ) ; } var minList = [ ] ; while ( minHeap . length > 0 ) { minList . push ( minHeap [ minHeap . length - 1 ] ) ; minHeap . pop ( ) ; } var mindiff = 1000000000 ; for ( var i = 0 ; i <= K ; i ++ ) { mindiff = Math . min ( mindiff , maxList [ i ] - minList [ K - i ] ) ; } return mindiff ; } var A = [ - 1 , 3 , - 1 , 8 , 5 , 4 ] ; var N = A . length ; var K = 3 ; document . write ( minDiff ( A , K , N ) ) ;