Open In App

Python3 Program to Maximize sum of diagonal of a matrix by rotating all rows or all columns

Given a square matrix, mat[][] of dimensions N * N, the task is find the maximum sum of diagonal elements possible from the given matrix by rotating either all the rows or all the columns of the matrix by a positive integer.

Examples:



Input: mat[][] = { { 1, 1, 2 }, { 2, 1, 2 }, { 1, 2, 2 } }
Output:
Explanation: 
Rotating all the columns of matrix by 1 modifies mat[][] to { {2, 1, 2}, {1, 2, 2}, {1, 1, 2} }. 
Therefore, the sum of diagonal elements of the matrix = 2 + 2 + 2 = 6 which is the maximum possible.

Input: A[][] = { { -1, 2 }, { -1, 3 } }
Output: 2



Approach: The idea is to rotate all the rows and columns of the matrix in all possible ways and calculate the maximum sum obtained. Follow the steps to solve the problem:

Below is the implementation of the above approach:




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

Output: 
6

 

Time Complexity: O(N2) 
Auxiliary Space: O(1)

Please refer complete article on Maximize sum of diagonal of a matrix by rotating all rows or all columns for more details!


Article Tags :