Maximum array sum that can be obtained after exactly k changes | Utility function to return the sum of the array elements ; Function to return the maximized sum of the array after performing the given operation exactly k times ; Sort the array elements ; Change signs of the negative elements starting from the smallest ; If a single operation has to be performed then it must be performed on the smallest positive element ; To store the index of the minimum element ; Update the minimum index ; Perform remaining operation on the smallest element ; Return the sum of the updated array ; Driver code
def sumArr ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT def maxSum ( arr , n , k ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE i = 0 NEW_LINE while ( i < n and k > 0 and arr [ i ] < 0 ) : NEW_LINE INDENT arr [ i ] *= - 1 NEW_LINE k -= 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( k % 2 == 1 ) : NEW_LINE INDENT min = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ min ] > arr [ i ] ) : NEW_LINE INDENT min = i NEW_LINE DEDENT DEDENT arr [ min ] *= - 1 NEW_LINE DEDENT return sumArr ( arr , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 5 , 4 , 1 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE print ( maxSum ( arr , n , k ) ) NEW_LINE DEDENT