Maximize array sum after K negations | Set 1 | Function to calculate sum of the array ; Iterate from 0 to n - 1 ; Function to maximize sum ; Iterate from 0 to n - 1 ; Driver Code ; Function Call
def sumArray ( 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 maximizeSum ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE i = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( k and arr [ i ] < 0 ) : NEW_LINE INDENT arr [ i ] *= - 1 NEW_LINE k -= 1 NEW_LINE continue NEW_LINE DEDENT break NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if ( k == 0 or k % 2 == 0 ) : NEW_LINE INDENT return sumArray ( arr , n ) NEW_LINE DEDENT if ( i != 0 and abs ( arr [ i ] ) >= abs ( arr [ i - 1 ] ) ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT arr [ i ] *= - 1 NEW_LINE return sumArray ( arr , n ) NEW_LINE DEDENT n = 5 NEW_LINE k = 4 NEW_LINE arr = [ - 3 , - 2 , - 1 , 5 , 6 ] NEW_LINE print ( maximizeSum ( arr , n , k ) ) NEW_LINE