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
def findMaxSumByAlternatingSign ( arr , N ) : NEW_LINE INDENT cntNeg = 0 NEW_LINE MaxAltSum = 0 NEW_LINE SmValue = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT cntNeg += 1 NEW_LINE DEDENT sum += abs ( arr [ i ] ) NEW_LINE SmValue = min ( SmValue , abs ( arr [ i ] ) ) NEW_LINE DEDENT MaxAltSum = sum NEW_LINE if ( cntNeg & 1 ) : NEW_LINE INDENT MaxAltSum -= 2 * SmValue NEW_LINE DEDENT return MaxAltSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , - 2 , - 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMaxSumByAlternatingSign ( arr , N ) ) NEW_LINE DEDENT