Maximum array sum that can be obtained after exactly k changes | Utility function to return the sum of the array elements ; Function to return the maximized sum of the array after performing the given operation exactly k times ; Sort the array elements ; Change signs of the negative elements starting from the smallest ; If a single operation has to be performed then it must be performed on the smallest positive element ; To store the index of the minimum element ; Update the minimum index ; Perform remaining operation on the smallest element ; Return the sum of the updated array ; Driver code
function sumArr ( arr , n ) { let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } function maxSum ( arr , n , k ) { arr . sort ( function ( a , b ) { return a - b } ) ; let i = 0 ; while ( i < n && k > 0 && arr [ i ] < 0 ) { arr [ i ] *= - 1 ; k -- ; i ++ ; } if ( k % 2 == 1 ) { let min = 0 ; for ( i = 1 ; i < n ; i ++ ) if ( arr [ min ] > arr [ i ] ) min = i ; arr [ min ] *= - 1 ; } return sumArr ( arr , n ) ; } let arr = [ - 5 , 4 , 1 , 3 , 2 ] ; let n = arr . length ; let k = 4 ; document . write ( maxSum ( arr , n , k ) ) ;