Maximize array sum by alternating the signs of adjacent elements | C ++ program to implement the above approach ; Function to find the maximum sum by alternating the signs of adjacent elements of the array ; Stores count of negative elements in the array ; Stores maximum sum by alternating the signs of adjacent elements ; Stores smallest absolute value of array elements ; Stores sum of absolute value of array elements ; Traverse the array ; If arr [ i ] is a negative number ; Update cntNeg ; Update sum ; Update SmValue ; Update MaxAltSum ; If cntNeg is an odd number ; Update MaxAltSum ; Drivers Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxSumByAlternatingSign ( int arr [ ] , int N ) { int cntNeg = 0 ; int MaxAltSum = 0 ; int SmValue = 0 ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { cntNeg += 1 ; } sum += abs ( arr [ i ] ) ; SmValue = min ( SmValue , abs ( arr [ i ] ) ) ; } MaxAltSum = sum ; if ( cntNeg & 1 ) { MaxAltSum -= 2 * SmValue ; } return MaxAltSum ; } int main ( ) { int arr [ ] = { 1 , 1 , -2 , -4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxSumByAlternatingSign ( arr , N ) ; }