Maximize sum of diagonal of a matrix by rotating all rows or all columns | Python3 program to implement the above approach ; Function to find maximum sum of diagonal elements of matrix by rotating either rows or columns ; Stores maximum diagonal sum of elements of matrix by rotating rows or columns ; Rotate all the columns by an integer in the range [ 0 , N - 1 ] ; Stores sum of diagonal elements of the matrix ; Calculate sum of diagonal elements of the matrix ; Update curr ; Update maxDiagonalSum ; Rotate all the rows by an integer in the range [ 0 , N - 1 ] ; Stores sum of diagonal elements of the matrix ; Calculate sum of diagonal elements of the matrix ; Update curr ; Update maxDiagonalSum ; Driver code
import sys NEW_LINE N = 3 NEW_LINE def findMaximumDiagonalSumOMatrixf ( A ) : NEW_LINE INDENT maxDiagonalSum = - sys . maxsize - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT curr += A [ j ] [ ( i + j ) % N ] NEW_LINE DEDENT maxDiagonalSum = max ( maxDiagonalSum , curr ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT curr = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT curr += A [ ( i + j ) % N ] [ j ] NEW_LINE DEDENT maxDiagonalSum = max ( maxDiagonalSum , curr ) NEW_LINE DEDENT return maxDiagonalSum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 1 , 2 ] , [ 2 , 1 , 2 ] , [ 1 , 2 , 2 ] ] NEW_LINE print ( findMaximumDiagonalSumOMatrixf ( mat ) ) NEW_LINE DEDENT