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 ; Perform K operations ; Stores smallest element in the array ; Stores index of the smallest array element ; Stores largest element in the array ; Stores index of the largest array element ; Traverse the array elements ; If current element exceeds largest_element ; Update the largest element ; Update index of the largest array element ; If current element is smaller than smallest_element ; Update the smallest element ; Update index of the smallest array element ; Stores the value of smallest element by given operations ; Stores the value of largest element by given operations ; If the value of a + b less than the sum of smallest and largest element of the array ; Update smallest element of the array ; Update largest element of the array ; Stores sum of elements of the array by given operations ; Traverse the array ; Update ans ; Driver Code
function minimum_possible_sum ( arr , n , k ) { if ( n == 0 ) { return 0 ; } if ( n == 1 ) { return arr [ 0 ] ; } for ( let i = 0 ; i < k ; i ++ ) { let smallest_element = arr [ 0 ] ; let smallest_pos = 0 ; let largest_element = arr [ 0 ] ; let largest_pos = 0 ; for ( let j = 1 ; j < n ; j ++ ) { if ( arr [ j ] >= largest_element ) { largest_element = arr [ j ] ; largest_pos = j ; } if ( arr [ j ] < smallest_element ) { smallest_element = arr [ j ] ; smallest_pos = j ; } } let a = smallest_element * 2 ; let b = largest_element / 2 ; if ( a + b < smallest_element + largest_element ) { arr [ smallest_pos ] = a ; arr [ largest_pos ] = b ; } } let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { ans += arr [ i ] ; } return ans ; } let arr = [ 50 , 1 , 100 , 100 , 1 ] ; let K = 2 ; let n = arr . length ; document . write ( minimum_possible_sum ( arr , n , K ) ) ;