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: 8
Explanation:
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: 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++ program for the above approach #include <bits/stdc++.h> using namespace std;
// Function to find the maximum sum of // matrix element after flipping the // signs of adjacent matrix elements int maxSum(vector<vector< int > >& matrix)
{ // Initialize row and column
int r = matrix.size();
int c = matrix[0].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<vector< int > > matrix
= { { 2, -2 }, { -2, 2 } };
cout << maxSum(matrix);
return 0;
} |
// 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. |
# 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# 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 |
<script> // JavaScript Program to implement
// the above approach
// Function to find the maximum sum of
// matrix element after flipping the
// signs of adjacent matrix elements
function maxSum(matrix) {
// Initialize row and column
let r = matrix.length;
let c = matrix[0].length;
// Stores the sum of absolute
// matrix element
let sum = 0;
// Find the minimum absolute value
// in the matrix
let mini = Number.MAX_VALUE;
// Store count of negatives
let count = 0;
for (let i = 0; i < r; i++) {
for (let j = 0; j < c; j++) {
let 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
let matrix
= [[2, -2], [-2, 2]];
document.write(maxSum(matrix));
// This code is contributed by Potta Lokesh </script>
|
8
Time Complexity: O(N2)
Auxiliary Space: O(1)