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
function sumArray ( arr , n ) { let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } return sum ; } function maximizeSum ( arr , n , k ) { ( arr ) . sort ( function ( a , b ) { return a - b ; } ) ; let i = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( k != 0 && arr [ i ] < 0 ) { arr [ i ] *= - 1 ; k -- ; continue ; } break ; } if ( i == n ) i -- ; if ( k == 0 k % 2 == 0 ) { return sumArray ( arr , n ) ; } if ( i != 0 && Math . abs ( arr [ i ] ) >= Math . abs ( arr [ i - 1 ] ) ) { i -- ; } arr [ i ] *= - 1 ; return sumArray ( arr , n ) ; } let n = 5 ; let k = 4 ; let arr = [ - 3 , - 2 , - 1 , 5 , 6 ] ; document . write ( maximizeSum ( arr , n , k ) ) ;