Minimize array sum by replacing greater and smaller elements of pairs by half and double of their values respectively atmost K times | C # implementation of the above approach ; 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
using System ; using System . Collections . Generic ; class GFG { static int minimum_possible_sum ( int [ ] arr , int n , int k ) { if ( n == 0 ) { return 0 ; } if ( n == 1 ) { return arr [ 0 ] ; } List < int > ms = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { ms . Add ( arr [ i ] ) ; } ms . Sort ( ) ; for ( int i = 0 ; i < k ; i ++ ) { int smallest_element = ms [ 0 ] ; int largest_element = ms [ ms . Count - 1 ] ; int a = smallest_element * 2 ; int b = largest_element / 2 ; if ( a + b < smallest_element + largest_element ) { ms . RemoveAt ( 0 ) ; ms . RemoveAt ( ms . Count - 1 ) ; ms . Add ( a ) ; ms . Add ( b ) ; ms . Sort ( ) ; } } int ans = 0 ; foreach ( int x in ms ) { ans += x ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 50 , 1 , 100 , 100 , 1 } ; int K = 2 ; int n = arr . Length ; Console . Write ( minimum_possible_sum ( arr , n , K ) ) ; } }