Maximize array sum after K negations | Set 1 | C ++ program to maximize array sum after k operations . ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int arr [ ] , int n , int k ) { for ( int i = 1 ; i <= k ; i ++ ) { int min = INT_MAX ; int index = -1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] < min ) { min = arr [ j ] ; index = j ; } } if ( min == 0 ) break ; arr [ index ] = - arr [ index ] ; } int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } int main ( ) { int arr [ ] = { -2 , 0 , 5 , -1 , 2 } ; int k = 4 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumSum ( arr , n , k ) ; return 0 ; }