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

• Last Updated : 16 Sep, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: mat[][] = [[2, -2], [-2, 2]]
OutputL: 8
Explanation:
Follow the steps below to find the maximum sum of matrix as:

1. Flipping the sign of adjacent element (arr, arr) modifies the matrix to mat[][] = {{-2, 2}, {-2, 2}}.
2. Flipping the sign of adjacent element (arr, arr) 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: 16

Approach: 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++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to find the maximum sum of``// matrix element after flipping the``// signs of adjacent matrix elements``int` `maxSum(vector >& matrix)``{` `    ``// Initialize row and column``    ``int` `r = matrix.size();``    ``int` `c = matrix.size();` `    ``// Stores the sum of absolute``    ``// matrix element``    ``int` `sum = 0;` `    ``// Find the minimum absolute value``    ``// in the matrix``    ``int` `mini = INT_MAX;` `    ``// Store count of negatives``    ``int` `count = 0;` `    ``for` `(``int` `i = 0; i < r; i++) {``        ``for` `(``int` `j = 0; j < c; j++) {``            ``int` `k = matrix[i][j];` `            ``// Find the smallest absolute``            ``// value in the matrix``            ``mini = min(mini, ``abs``(k));` `            ``// Increment the count of``            ``// negative numbers``            ``if` `(k < 0)``                ``count++;` `            ``// Find the absolute sum``            ``sum += ``abs``(k);``        ``}``    ``}` `    ``// If the count of negatives is``    ``// even then print the sum``    ``if` `(count % 2 == 0) {``        ``return` `sum;``    ``}` `    ``// Subtract minimum absolute``    ``// element``    ``else` `{``        ``return` `(sum - 2 * mini);``    ``}``}` `// Driver Code``int` `main()``{``    ``vector > matrix``        ``= { { 2, -2 }, { -2, 2 } };``    ``cout << maxSum(matrix);` `    ``return` `0;``}`

## Java

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

## Python3

 `# Python 3 program for the above approach``import` `sys` `# Function to find the maximum sum of``# matrix element after flipping the``# signs of adjacent matrix elements``def` `maxSum(matrix):``    ``# Initialize row and column``    ``r ``=` `len``(matrix)``    ``c ``=` `len``(matrix[``0``])` `    ``# Stores the sum of absolute``    ``# matrix element``    ``sum` `=` `0` `    ``# Find the minimum absolute value``    ``# in the matrix``    ``mini ``=` `sys.maxsize` `    ``# Store count of negatives``    ``count ``=` `0` `    ``for` `i ``in` `range``(r):``        ``for` `j ``in` `range``(c):``            ``k ``=` `matrix[i][j]` `            ``# Find the smallest absolute``            ``# value in the matrix``            ``mini ``=` `min``(mini, ``abs``(k))` `            ``# Increment the count of``            ``# negative numbers``            ``if` `(k < ``0``):``                ``count ``+``=` `1` `            ``# Find the absolute sum``            ``sum` `+``=` `abs``(k)` `    ``# If the count of negatives is``    ``# even then print the sum``    ``if` `(count ``%` `2` `=``=` `0``):``        ``return` `sum` `    ``# Subtract minimum absolute``    ``# element``    ``else``:``        ``return` `(``sum` `-` `2` `*` `mini)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``matrix ``=` `[[``2``, ``-``2``],[``-``2``, ``2``]]``    ``print``(maxSum(matrix))``    ` `    ``# This code is contributed by ipg2016107.`

## C#

 `// C# program for the above approach``using` `System;` `public` `class` `GFG``{` `    ``// Function to find the maximum sum of``    ``// matrix element after flipping the``    ``// signs of adjacent matrix elements``    ``static` `int` `maxSum(``int``[,] matrix)``    ``{` `        ``// Initialize row and column``        ``int` `r = matrix.GetLength(0);``        ``int` `c = matrix.GetLength(1);` `        ``// Stores the sum of absolute``        ``// matrix element``        ``int` `sum = 0;` `        ``// Find the minimum absolute value``        ``// in the matrix``        ``int` `mini = ``int``.MaxValue;` `        ``// Store count of negatives``        ``int` `count = 0;` `        ``for` `(``int` `i = 0; i < r; i++) {``            ``for` `(``int` `j = 0; j < c; j++) {``                ``int` `k = matrix[i,j];` `                ``// Find the smallest absolute``                ``// value in the matrix``                ``mini = Math.Min(mini, Math.Abs(k));` `                ``// Increment the count of``                ``// negative numbers``                ``if` `(k < 0)``                    ``count++;` `                ``// Find the absolute sum``                ``sum += Math.Abs(k);``            ``}``        ``}` `        ``// If the count of negatives is``        ``// even then print the sum``        ``if` `(count % 2 == 0) {``            ``return` `sum;``        ``}` `        ``// Subtract minimum absolute``        ``// element``        ``else` `{``            ``return` `(sum - 2 * mini);``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``int``[,] matrix = { { 2, -2 }, { -2, 2 } };``        ``Console.Write(maxSum(matrix));``    ``}``}` `// This code is contributed by AnkThon`

## Javascript

 ``

Output:
`8`

Time Complexity: O(N2)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up