Maximize matrix sum by repeatedly multiplying pairs of adjacent elements with | Java program to implement the above approach ; Store the maximum sum of matrix possible ; Stores the count of negative values in the matrix ; Store minimum absolute value present in the matrix ; Traverse the matrix row - wise ; Update sum ; If current element is negative , increment the negative count ; If current value is less than the overall minimum in A [ ] , update the overall minimum ; If there are odd number of negative values , then the answer will be sum of the absolute values of all elements - 2 * minVal ; Print maximum sum ; Driver Code ; Given matrix ; Dimensions of matrix
import java . io . * ; class GFG { static void getMaxSum ( int [ ] [ ] A , int M , int N ) { int sum = 0 ; int negative = 0 ; int minVal = Integer . MAX_VALUE ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { sum += Math . abs ( A [ i ] [ j ] ) ; if ( A [ i ] [ j ] < 0 ) { negative ++ ; } minVal = Math . min ( minVal , Math . abs ( A [ i ] [ j ] ) ) ; } } if ( negative % 2 != 0 ) { sum -= 2 * minVal ; } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int [ ] [ ] A = { { 4 , - 8 , 6 } , { 3 , 7 , 2 } } ; int M = A . length ; int N = A [ 0 ] . length ; getMaxSum ( A , M , N ) ; } }