Maximize array sum after K negations | Set 1 | Python3 program to find maximum array sum after at most k negations ; Sorting given array using in - built java sort function ; If we find a 0 in our sorted array , we stop ; Calculating sum ; Driver code
def sol ( arr , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE Sum = 0 NEW_LINE i = 0 NEW_LINE while ( k > 0 ) : NEW_LINE INDENT if ( arr [ i ] >= 0 ) : NEW_LINE INDENT k = 0 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = ( - 1 ) * arr [ i ] NEW_LINE k = k - 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT for j in range ( len ( arr ) ) : NEW_LINE INDENT Sum += arr [ j ] NEW_LINE DEDENT return Sum NEW_LINE DEDENT arr = [ - 2 , 0 , 5 , - 1 , 2 ] NEW_LINE print ( sol ( arr , 4 ) ) NEW_LINE