Minimize Sum of an Array by at most K reductions | Function to obtain the minimum possible sum from the array by K reductions ; Implements the MaxHeap ; Insert elements into the MaxHeap ; Remove the maximum ; Insert maximum / 2 ; Stores the sum of remaining elements ; Driver Code
function minSum ( a , n , k ) { let maxheap = [ ] ; for ( let i = 0 ; i < n ; i ++ ) maxheap . push ( a [ i ] ) ; maxheap . sort ( function ( a , b ) { return a - b ; } ) ; while ( maxheap . length > 0 && k > 0 ) { let max_ele = maxheap . pop ( ) ; maxheap . push ( Math . floor ( max_ele / 2 ) ) ; k -= 1 ; maxheap . sort ( function ( a , b ) { return a - b ; } ) ; } let sum = 0 ; while ( maxheap . length > 0 ) sum += maxheap . shift ( ) ; return sum ; } let n = 4 ; let k = 3 ; let a = [ 20 , 7 , 5 , 4 ] ; document . write ( minSum ( a , n , k ) ) ;