Maximize sum of diagonal of a matrix by rotating all rows or all columns | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N  3 NEW_LINE int findMaximumDiagonalSumOMatrixf ( int A [ ] [ N ] ) { int maxDiagonalSum = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { int curr = 0 ; for ( int j = 0 ; j < N ; j ++ ) { curr += A [ j ] [ ( i + j ) % N ] ; } maxDiagonalSum = max ( maxDiagonalSum , curr ) ; } for ( int i = 0 ; i < N ; i ++ ) { int curr = 0 ; for ( int j = 0 ; j < N ; j ++ ) { curr += A [ ( i + j ) % N ] [ j ] ; } maxDiagonalSum = max ( maxDiagonalSum , curr ) ; } return maxDiagonalSum ; } int main ( ) { int mat [ N ] [ N ] = { { 1 , 1 , 2 } , { 2 , 1 , 2 } , { 1 , 2 , 2 } } ; cout << findMaximumDiagonalSumOMatrixf ( mat ) ; return 0 ; }