Maximize matrix sum by flipping the sign of any adjacent pairs | Java program for the above approach ; Function to find the maximum sum of matrix element after flipping the signs of adjacent matrix elements ; Initialize row and column ; Stores the sum of absolute matrix element ; Find the minimum absolute value in the matrix ; Store count of negatives ; Find the smallest absolute value in the matrix ; Increment the count of negative numbers ; Find the absolute sum ; If the count of negatives is even then print the sum ; Subtract minimum absolute element ; Driver Code
import java . util . * ; class GFG { static int maxSum ( int [ ] [ ] matrix ) { int r = matrix . length ; int c = matrix [ 0 ] . length ; int sum = 0 ; int mini = Integer . MAX_VALUE ; int count = 0 ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { int k = matrix [ i ] [ j ] ; mini = Math . min ( mini , Math . abs ( k ) ) ; if ( k < 0 ) count ++ ; sum += Math . abs ( k ) ; } } if ( count % 2 == 0 ) { return sum ; } else { return ( sum - 2 * mini ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] matrix = { { 2 , - 2 } , { - 2 , 2 } } ; System . out . print ( maxSum ( matrix ) ) ; } }