# Maximize matrix sum by flipping the sign of any adjacent pairs

Given a matrix mat[] of dimension N*N, the task is to find the maximum sum of matrix elements by flipping the signs of the adjacent element any number of times.Examples:Input: mat[][] = [[2, -2], [-2, 2]]OutputL: 8Explanation:Follow the steps below to find the maximum sum of matrix as:Flipping the sign of adjacent element (arr[0][0], arr[0][1]) modifies the matrix to mat[][] = {{-2, 2}, {-2, 2}}.Flipping the sign of adjacent element (arr[0][0], arr[1][0]) modifies the matrix to mat[][] = {{2, 2}, {2, 2}}.Now, the sum of matrix elements is 8, which is the maximum among all possible flipping of adjacent matrix elements.Input: mat[][] = [[1, 2, 3], [-1, -2, -3], [1, 2, 3]]Output: 16Approach: The given problem can be solved by observing the fact that if there are an even number of negatives in the matrix, then all those elements can be converted to positive elements to get the maximum sum. Otherwise, all matrix elements can be flipped except the one negative elements. Follow the steps below to solve the problem:Find the sum of absolute values of all matrix elements and store it in a variable say S.Find the matrix element with minimum absolute values and store it in a variable say minElement.If the count of negative elements in the given matrix mat[][] is even, then print the maximum sum as S. Otherwise, print the value of (S – 2*minElement) as the resultant sum by excluding the minimum element in the sum.Below is the implementation of the above approach:C++#include using namespace std; int maxSum(vector& 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 matrix = { { 2, -2 }, { -2, 2 } }; cout