Maximize array sum after K negations | Set 1 | This function does k operations on array in a way that maximize the array sum . index -- > stores the index of current minimum element for j 'th operation ; Modify array K number of times ; Find minimum element in array for current operation and modify it i . e ; arr [ j ] -- > - arr [ j ] ; this the condition if we find 0 as minimum element , so it will useless to replace 0 by - ( 0 ) for remaining operations ; Modify element of array ; Calculate sum of array ; Driver code
def maximumSum ( arr , n , k ) : NEW_LINE INDENT for i in range ( 1 , k + 1 ) : NEW_LINE INDENT min = + 2147483647 NEW_LINE index = - 1 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] < min ) : NEW_LINE INDENT min = arr [ j ] NEW_LINE index = j NEW_LINE DEDENT DEDENT if ( min == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT arr [ index ] = - arr [ index ] NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ - 2 , 0 , 5 , - 1 , 2 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE print ( maximumSum ( arr , n , k ) ) NEW_LINE