Maximize array sum after K negations | Set 1 | JavaScript 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
function sol ( arr , k ) { arr . sort ( ) ; let sum = 0 ; let i = 0 ; while ( k > 0 ) { if ( arr [ i ] >= 0 ) k = 0 ; else { arr [ i ] = ( - 1 ) * arr [ i ] ; k = k - 1 ; } i ++ ; } for ( let j = 0 ; j < arr . length ; j ++ ) { sum += arr [ j ] ; } return sum ; } let arr = [ - 2 , 0 , 5 , - 1 , 2 ] ; document . write ( sol ( arr , 4 ) ) ;