Maximize matrix sum by flipping the sign of any adjacent pairs | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( vector < vector < int > > & matrix ) { int r = matrix . size ( ) ; int c = matrix [ 0 ] . size ( ) ; int sum = 0 ; int mini = INT_MAX ; int count = 0 ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { int k = matrix [ i ] [ j ] ; mini = min ( mini , abs ( k ) ) ; if ( k < 0 ) count ++ ; sum += abs ( k ) ; } } if ( count % 2 == 0 ) { return sum ; } else { return ( sum - 2 * mini ) ; } } int main ( ) { vector < vector < int > > matrix = { { 2 , -2 } , { -2 , 2 } } ; cout << maxSum ( matrix ) ; return 0 ; }