Maximize array sum by alternating the signs of adjacent elements | Java 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 ; Driver Code
import java . util . * ; class GFG { static 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 += Math . abs ( arr [ i ] ) ; SmValue = Math . min ( SmValue , Math . abs ( arr [ i ] ) ) ; } MaxAltSum = sum ; if ( cntNeg % 2 == 1 ) { MaxAltSum -= 2 * SmValue ; } return MaxAltSum ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , - 2 , - 4 , 5 } ; int N = arr . length ; System . out . print ( findMaxSumByAlternatingSign ( arr , N ) ) ; } }