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