Maximize matrix sum by repeatedly multiplying pairs of adjacent elements with | Python3 program to implement the above approach ; Function to calculate maximum sum possible of a matrix by multiplying pairs of adjacent elements with - 1 any number of times ( possibly zero ) ; Store the maximum sum of matrix possible ; Stores the count of negative values in the matrix ; Store minimum absolute value present in the matrix ; Traverse the matrix row - wise ; Update sum ; If current element is negative , increment the negative count ; If current value is less than the overall minimum in A [ ] , update the overall minimum ; If there are odd number of negative values , then the answer will be sum of the absolute values of all elements - 2 * minVal ; Print maximum sum ; Driver Code ; Given matrix ; Dimensions of matrix
import sys NEW_LINE def getMaxSum ( A , M , N ) : NEW_LINE INDENT sum = 0 NEW_LINE negative = 0 NEW_LINE minVal = sys . maxsize NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT sum += abs ( A [ i ] [ j ] ) NEW_LINE if ( A [ i ] [ j ] < 0 ) : NEW_LINE INDENT negative += 1 NEW_LINE DEDENT minVal = min ( minVal , abs ( A [ i ] [ j ] ) ) NEW_LINE DEDENT DEDENT if ( negative % 2 ) : NEW_LINE INDENT sum -= 2 * minVal NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ [ 4 , - 8 , 6 ] , [ 3 , 7 , 2 ] ] NEW_LINE M = len ( A ) NEW_LINE N = len ( A [ 0 ] ) NEW_LINE getMaxSum ( A , M , N ) NEW_LINE DEDENT