Maximize sum of diagonal of a matrix by rotating all rows or all columns | Java 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 java . util . * ; class GFG { static int N = 3 ; static int findMaximumDiagonalSumOMatrixf ( int A [ ] [ ] ) { int maxDiagonalSum = Integer . MIN_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { int curr = 0 ; for ( int j = 0 ; j < N ; j ++ ) { curr += A [ j ] [ ( i + j ) % N ] ; } maxDiagonalSum = Math . 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 = Math . max ( maxDiagonalSum , curr ) ; } return maxDiagonalSum ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 1 , 2 } , { 2 , 1 , 2 } , { 1 , 2 , 2 } } ; System . out . println ( findMaximumDiagonalSumOMatrixf ( mat ) ) ; } }