Given a matrix A[][] of dimensions M × N, the task is to find the maximum sum possible from a matrix by repeatedly selecting two adjacent matrix elements and multiplying both of their values with -1.
Examples:
Input: A[ ][ ] = {{4, -8, 6}, {3, 7, 2}}
Output: 26
Explanation:
Multiply mat[0][1] and mat[0][2] by -1. The matrix modifies to A[][] = {{4, 8, -6}, {3, 7, 2}}.
Multiply mat[0][2] and mat[1][2] by -1. The matrix modifies to A[][] = {{4, 8, 6}, {3, 7, -2}}.
Therefore, sum of the matrix = 26, which is the maximum sum possible.Input: A[ ][ ] = {{2, 9, -5}, {6, 1, 3}, {-7, 4, 8}}
Output: 45
Explanation:
Multiply mat[0][2] and mat[1][2] by -1. The matrix modifies to A[][] = {{2, 9, 5}, {6, 1, -3}, {-7, 4, 8}}.
Multiply mat[1][1] and mat[1][2] by -1. The matrix modifies to A[][] = {{2, 9, 5}, {6, -1, 3}, {-7, 4, 8}}.
Multiply mat[1][1] and mat[2][1] by -1. The matrix modifies to A[][] = {{2, 9, 5}, {6, 1, 3}, {-7, -4, 8}}.
Multiply mat[2][0] and mat[2][1] by -1. The matrix modifies to A[][] = {{2, 9, 5}, {6, 1, 3}, {7, 4, 8}}.
Therefore, sum of the matrix = 45, which is the maximum sum possible.
Approach: To maximize the sum of the given matrix, perform the given operations such that the smallest element in a row or column is negative (if it is not possible to make all row and column elements positive). Follow the steps below to maximize the sum:
- Let the number of cells having negative values be x. If x is 0 i.e., there are no negative values, then the sum of the matrix is already maximum possible.
- Otherwise, take any negative value from the matrix and perform the given operations on that element and any of its adjacent cells. This results in the chosen element becoming positive.
- Now if the value of the chosen adjacent element is negative, then it will become positive or vice versa. This way, in each turn two negative values can be made positive. Now following two cases arise:
- If x is even: In this case, after x/2 turns, all the negative values can be made positive. Therefore, the maximum sum possible is equal to the sum of the absolute values of all cells.
- If x is odd: In this case, there will be one negative value left after performing operations in the manner described above. Now, to maximize the sum, the value getting subtracted or having a negative sign needs to be minimized. To do this, move the negative sign to the cell having minimum absolute value, say minVal. Therefore, the maximum sum possible is sum of the absolute values of all cells – 2*minVal.
Below is the implementation of the above approach:
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate maximum sum // possible of a matrix by multiplying // pairs of adjacent elements with -1 // any number of times (possibly zero) void getMaxSum(vector<vector< int > > A, int M, int N) { // Store the maximum sum // of matrix possible int sum = 0; // Stores the count of // negative values in the matrix int negative = 0; // Store minimum absolute // value present in the matrix int minVal = INT_MAX; // Traverse the matrix row-wise for ( int i = 0; i < M; i++) { for ( int j = 0; j < N; j++) { // Update sum sum += abs (A[i][j]); // If current element is negative, // increment the negative count if (A[i][j] < 0) { negative++; } // If current value is less than // the overall minimum in A[], // update the overall minimum minVal = min(minVal, abs (A[i][j])); } } // If there are odd number of negative // values, then the answer will be // sum of the absolute values of // all elements - 2* minVal if (negative % 2) { sum -= 2 * minVal; } // Print maximum sum cout << sum; } // Driver Code int main() { // Given matrix vector<vector< int > > A = { { 4, -8, 6 }, { 3, 7, 2 } }; // Dimensions of matrix int M = A.size(); int N = A[0].size(); getMaxSum(A, M, N); return 0; } |
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { static void getMaxSum( int [][] A, int M, int N) { // Store the maximum sum // of matrix possible int sum = 0 ; // Stores the count of // negative values in the matrix int negative = 0 ; // Store minimum absolute // value present in the matrix int minVal = Integer.MAX_VALUE; // Traverse the matrix row-wise for ( int i = 0 ; i < M; i++) { for ( int j = 0 ; j < N; j++) { // Update sum sum += Math.abs(A[i][j]); // If current element is negative, // increment the negative count if (A[i][j] < 0 ) { negative++; } // If current value is less than // the overall minimum in A[], // update the overall minimum minVal = Math.min(minVal, Math.abs(A[i][j])); } } // If there are odd number of negative // values, then the answer will be // sum of the absolute values of // all elements - 2* minVal if (negative % 2 != 0 ) { sum -= 2 * minVal; } // Print maximum sum System.out.println(sum); } // Driver Code public static void main(String[] args) { // Given matrix int [][] A = { { 4 , - 8 , 6 }, { 3 , 7 , 2 } }; // Dimensions of matrix int M = A.length; int N = A[ 0 ].length; getMaxSum(A, M, N); } } // This code is contributed by aditya7409. |
Python3
# Python3 program to implement # the above approach import sys # Function to calculate maximum sum # possible of a matrix by multiplying # pairs of adjacent elements with -1 # any number of times (possibly zero) def getMaxSum(A, M, N): # Store the maximum sum # of matrix possible sum = 0 # Stores the count of # negative values in the matrix negative = 0 # Store minimum absolute # value present in the matrix minVal = sys.maxsize # Traverse the matrix row-wise for i in range (M): for j in range (N): # Update sum sum + = abs (A[i][j]) # If current element is negative, # increment the negative count if (A[i][j] < 0 ): negative + = 1 # If current value is less than # the overall minimum in A[], # update the overall minimum minVal = min (minVal, abs (A[i][j])) # If there are odd number of negative # values, then the answer will be # sum of the absolute values of # all elements - 2* minVal if (negative % 2 ): sum - = 2 * minVal # Print maximum sum print ( sum ) # Driver Code if __name__ = = '__main__' : # Given matrix A = [[ 4 , - 8 , 6 ], [ 3 , 7 , 2 ]] # Dimensions of matrix M = len (A) N = len (A[ 0 ]) getMaxSum(A, M, N) # This code is contributed by ipg2016107. |
C#
// C# program to implement // the above approach using System; class GFG{ // Function to calculate maximum sum // possible of a matrix by multiplying // pairs of adjacent elements with -1 // any number of times (possibly zero) static void getMaxSum( int [,] A, int M, int N) { // Store the maximum sum // of matrix possible int sum = 0; // Stores the count of // negative values in the matrix int negative = 0; // Store minimum absolute // value present in the matrix int minVal = Int32.MaxValue; // Traverse the matrix row-wise for ( int i = 0; i < M; i++) { for ( int j = 0; j < N; j++) { // Update sum sum += Math.Abs(A[i, j]); // If current element is negative, // increment the negative count if (A[i, j] < 0) { negative++; } // If current value is less than // the overall minimum in A[], // update the overall minimum minVal = Math.Min(minVal, Math.Abs(A[i, j])); } } // If there are odd number of negative // values, then the answer will be // sum of the absolute values of // all elements - 2* minVal if (negative % 2 != 0) { sum -= 2 * minVal; } // Print maximum sum Console.Write(sum); } // Driver Code public static void Main() { // Given matrix int [, ] A = { { 4, -8, 6 }, { 3, 7, 2 } }; // Dimensions of matrix int M = A.GetLength(0); int N = A.GetLength(1); getMaxSum(A, M, N); } } // This code is contributed by chitranayal |
Javascript
<script> //java script code function getMaxSum(A,M,N) { // Store the maximum sum // of matrix possible let sum = 0; // Stores the count of // negative values in the matrix let negative = 0; // Store minimum absolute // value present in the matrix let minVal = Number.MAX_VALUE; // Traverse the matrix row-wise for (let i = 0; i < M; i++) { for (let j = 0; j < N; j++) { // Update sum sum += Math.abs(A[i][j]); // If current element is negative, // increment the negative count if (A[i][j] < 0) { negative++; } // If current value is less than // the overall minimum in A[], // update the overall minimum minVal = Math.min(minVal, Math.abs(A[i][j])); } } // If there are odd number of negative // values, then the answer will be // sum of the absolute values of // all elements - 2* minVal if (negative % 2 != 0) { sum -= 2 * minVal; } // Print maximum sum document.write(sum); } // Driver Code // Given matrix let A = [[4, -8, 6 ], [ 3, 7, 2 ]]; // Dimensions of matrix let M = A.length; let N = A[0].length; getMaxSum(A, M, N); // This code is contributed by sravan kumar Gottumukkala </script> |
26
Time Complexity: O(M*N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!