Maximum value after merging all elements in the array | Function to maximum value after merging all elements in the array ; To check if positive and negative elements present or not ; Check for positive integer ; Check for negative integer ; If both positive and negative elements are present ; To store maximum value possible ; To find minimum value ; Remove minimum element ; Replace with absolute values ; To find minimum value ; Remove minimum element ; Return the required sum ; Driver code ; Function call
function Max_sum ( a , n ) { let pos = 0 , neg = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] > 0 ) pos = 1 ; else if ( a [ i ] < 0 ) neg = 1 ; if ( pos == 1 && neg == 1 ) break ; } let sum = 0 ; if ( pos == 1 && neg == 1 ) { for ( let i = 0 ; i < n ; i ++ ) sum += Math . abs ( a [ i ] ) ; } else if ( pos == 1 ) { let mini = a [ 0 ] ; sum = a [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { mini = Math . min ( mini , a [ i ] ) ; sum += a [ i ] ; } sum -= 2 * mini ; } else if ( neg == 1 ) { for ( let i = 0 ; i < n ; i ++ ) a [ i ] = Math . abs ( a [ i ] ) ; let mini = a [ 0 ] ; sum = a [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { mini = Math . min ( mini , a [ i ] ) ; sum += a [ i ] ; } sum -= 2 * mini ; } return sum ; } let a = [ 1 , 3 , 5 , - 2 , - 6 ] ; let n = a . length ; document . write ( Max_sum ( a , n ) ) ;