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
def minimum_possible_sum ( arr , n , k ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT smallest_element = arr [ 0 ] NEW_LINE smallest_pos = 0 NEW_LINE largest_element = arr [ 0 ] NEW_LINE largest_pos = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] >= largest_element ) : NEW_LINE INDENT largest_element = arr [ i ] NEW_LINE largest_pos = i NEW_LINE DEDENT if ( arr [ i ] < smallest_element ) : NEW_LINE INDENT smallest_element = arr [ i ] NEW_LINE smallest_pos = i NEW_LINE DEDENT DEDENT a = smallest_element * 2 NEW_LINE b = largest_element // 2 NEW_LINE if ( a + b < smallest_element + largest_element ) : NEW_LINE INDENT arr [ smallest_pos ] = a NEW_LINE arr [ largest_pos ] = b NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += arr [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 50 , 1 , 100 , 100 , 1 ] NEW_LINE K = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( minimum_possible_sum ( arr , n , K ) ) NEW_LINE DEDENT