Minimize array sum by replacing greater and smaller elements of pairs by half and double of their values respectively atmost K times | Function to find the minimum sum of array elements by given operations ; Base case ; Return 0 ; Base case ; Stores all the array elements in sorted order ; Traverse the array ; Insert current element into multiset ; Perform each operation ; Stores smallest element of ms ; Stores the largest element of ms ; Stores updated value of smallest element of ms by given operations ; Stores updated value of largest element of ms by given operations ; If the value of a + b less than the sum of smallest and largest array element ; Erase the smallest element ; Erase the largest element ; Insert the updated value of the smallest element ; Insert the updated value of the smallest element ; Stores sum of array elements ; Traverse the multiset ; Update ans ; Driver Code
function minimum_possible_sum ( arr , n , k ) { if ( n == 0 ) { return 0 ; } if ( n == 1 ) { return arr [ 0 ] ; } var ms = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { ms . push ( arr [ i ] ) ; } ms . sort ( ( a , b ) => a - b ) for ( var i = 0 ; i < k ; i ++ ) { var smallest_element = ms [ 0 ] ; var largest_element = ms [ ms . length - 1 ] ; var a = smallest_element * 2 ; var b = largest_element / 2 ; if ( a + b < smallest_element + largest_element ) { ms . shift ( ) ; ms . pop ( ) ; ms . push ( a ) ; ms . push ( b ) ; ms . sort ( ( a , b ) => a - b ) } } var ans = 0 ; ms . forEach ( x => { ans += x ; } ) ; return ans ; } var arr = [ 50 , 1 , 100 , 100 , 1 ] ; var K = 2 ; var n = arr . length ; document . write ( minimum_possible_sum ( arr , n , K ) ) ;