text: Maximum value after merging all elements in the array | Java program to 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
code: import java . io . * ; class GFG { static int Max_sum ( int a [ ] , int n ) { int pos = 0 , neg = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > 0 ) pos = 1 ; else if ( a [ i ] < 0 ) neg = 1 ; if ( ( pos == 1 ) && ( neg == 1 ) ) break ; } int sum = 0 ; if ( ( pos == 1 ) && ( neg == 1 ) ) { for ( int i = 0 ; i < n ; i ++ ) sum += Math . abs ( a [ i ] ) ; } else if ( pos == 1 ) { int mini = a [ 0 ] ; sum = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { mini = Math . min ( mini , a [ i ] ) ; sum += a [ i ] ; } sum -= 2 * mini ; } else if ( neg == 1 ) { for ( int i = 0 ; i < n ; i ++ ) a [ i ] = Math . abs ( a [ i ] ) ; int mini = a [ 0 ] ; sum = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { mini = Math . min ( mini , a [ i ] ) ; sum += a [ i ] ; } sum -= 2 * mini ; } return sum ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 3 , 5 , - 2 , - 6 } ; int n = a . length ; System . out . println ( Max_sum ( a , n ) ) ; } }