Maximize array sum by alternating the signs of adjacent elements | 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 ; Driver Code
function findMaxSumByAlternatingSign ( arr , N ) { let cntNeg = 0 ; let MaxAltSum = 0 ; let SmValue = 0 ; let sum = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { cntNeg += 1 ; } sum += Math . abs ( arr [ i ] ) ; SmValue = Math . min ( SmValue , Math . abs ( arr [ i ] ) ) ; } MaxAltSum = sum ; if ( cntNeg % 2 == 1 ) { MaxAltSum -= 2 * SmValue ; } return MaxAltSum ; } let arr = [ 1 , 1 , - 2 , - 4 , 5 ] ; let N = arr . length ; document . write ( findMaxSumByAlternatingSign ( arr , N ) ) ;