Minimize remaining array element by removing pairs and replacing them with their average | Function to find the smallest element left in the array by removing pairs and inserting their average ; Stores array elements such that the largest element present at top of PQ ; Traverse the array ; Insert arr [ i ] into PQ ; Iterate over elements of PQ while count of elements in PQ greater than 1 ; Stores largest element of PQ ; Pop the largest element of PQ ; Stores largest element of PQ ; Pop the largest element of PQ ; Insert the ceil value of average of top1 and top2 ; Driver Code
function findSmallestNumLeft ( arr , N ) { let PQ = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { PQ . push ( arr [ i ] ) ; } PQ . sort ( function ( a , b ) { return b - a ; } ) ; while ( PQ . length > 1 ) { let top1 = PQ [ 0 ] ; PQ . shift ( ) ; let top2 = PQ [ 0 ] ; PQ . shift ( ) ; PQ . push ( Math . floor ( ( top1 + top2 + 1 ) / 2 ) ) ; PQ . sort ( function ( a , b ) { return b - a ; } ) ; } return PQ [ 0 ] ; } let arr = [ 30 , 16 , 40 ] ; let N = arr . length ; document . write ( findSmallestNumLeft ( arr , N ) ) ;