Maximize matrix sum by repeatedly multiplying pairs of adjacent elements with | C ++ program to implement the above approach ; Function to calculate maximum sum possible of a matrix by multiplying pairs of adjacent elements with - 1 any number of times ( possibly zero ) ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getMaxSum ( vector < vector < int > > A , int M , int N ) { int sum = 0 ; int negative = 0 ; int minVal = INT_MAX ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { sum += abs ( A [ i ] [ j ] ) ; if ( A [ i ] [ j ] < 0 ) { negative ++ ; } minVal = min ( minVal , abs ( A [ i ] [ j ] ) ) ; } } if ( negative % 2 ) { sum -= 2 * minVal ; } cout << sum ; } int main ( ) { vector < vector < int > > A = { { 4 , -8 , 6 } , { 3 , 7 , 2 } } ; int M = A . size ( ) ; int N = A [ 0 ] . size ( ) ; getMaxSum ( A , M , N ) ; return 0 ; }