Maximum sum of elements in a diagonal parallel to the main diagonal of a given Matrix
Last Updated :
31 Aug, 2023
Give a square matrix mat[][] of dimensions N * N, the task is to find the maximum sum of elements present in the given matrix along the diagonals which are parallel to the main diagonal. Below is the image of the same.

Examples:
Input: mat[][] = {{1, 2, 5, 7}, {2, 6, 7, 3}, {12, 3, 2, 4}, {3, 6, 9, 4}}
Output: 18
Explanation:
Sum of elements present in the diagonal having cells (2, 0) and (3, 1) is 12 + 6 = 18 which is maximum among all diagonals.
Input: mat[][] = {{5, 2, 5, 7}, {2, 5, 7, 3}, {12, 3, 5, 4}, {3, 6, 9, 5}}
Output: 18
Explanation:
Sum of elements present in the main diagonal having cells (0, 0), (1, 1), (2, 2) and (3, 3) is 5 + 5 + 5 + 5 = 20 which is maximum among all diagonals.
Approach: The idea is to traverse cells of each diagonal that is parallel to the main diagonal and observe that for any diagonal above the main diagonal starting at cell (x, y), it's corresponding diagonal that is below the main diagonal will start at cell (y, x). For each diagonal, starting at cell (x, y) all its elements will be on cells (x + k, y + k) where 0 <= x + k, y + k < N. Follow the below steps to solve the problem:
- Initialize a variable maxSum with 0 which will store the maximum diagonal sum.
- Traverse the columns of 0th row from i over the range [0, N - 1].
- Initialize variables sum1 and sum2 which will store the diagonal sums starting from the cell (row, col) and from the cell (col, row) respectively where r is 0 and c is col.
- Increment both row and c by 1. Add mat[row][col] to sum1 and mat[col][row] to sum2 while row and col are smaller than N. Finally, update maxSum to store the maximum of maxSum, sum1, and sum2.
- After traversing the given matrix, print the value maxSum as the maximum sum.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return maximum diagonal
// sum that are parallel to main diagonal
int maxDiagonalSum(vector<vector<int> > arr, int N)
{
// Initialize maxSum
int maxSum = 0;
// Traverse through the columns
for (int i = 0; i < N; i++) {
// Initialize r and c
int row = 0, col = i;
// Diagonal sums
int sum1 = 0, sum2 = 0;
while (col < N && row < N) {
sum1 += arr[row][col];
sum2 += arr[col][row];
row++;
col++;
}
// Update maxSum with
// the maximum sum
maxSum = max({ sum1, maxSum, sum2 });
}
// Return the maxSum
return maxSum;
}
// Driver Code
int main()
{
// Given matrix mat[][]
vector<vector<int> > mat
= { { 1, 2, 5, 7 },
{ 2, 6, 7, 3 },
{ 12, 3, 2, 4 },
{ 3, 6, 9, 4 } };
int N = mat.size();
// Function Call
cout << maxDiagonalSum(mat, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG{
// Function to return maximum diagonal
// sum that are parallel to main diagonal
static int maxDiagonalSum(int arr[][], int N)
{
// Initialize maxSum
int maxSum = 0;
// Traverse through the columns
for(int i = 0; i < N; i++)
{
// Initialize r and c
int row = 0, col = i;
// Diagonal sums
int sum1 = 0, sum2 = 0;
while (col < N && row < N)
{
sum1 += arr[row][col];
sum2 += arr[col][row];
row++;
col++;
}
// Update maxSum with
// the maximum sum
maxSum = Math.max(maxSum,
Math.max(sum1,
sum2));
}
// Return the maxSum
return maxSum;
}
// Driver code
public static void main (String[] args)
{
// Given matrix mat[][]
int mat[][] = { { 1, 2, 5, 7 },
{ 2, 6, 7, 3 },
{ 12, 3, 2, 4 },
{ 3, 6, 9, 4 } };
int N = mat.length;
// Function Call
System.out.println(maxDiagonalSum(mat, N));
}
}
// This code is contributed by math_lover
Python3
# Python3 program for the above approach
# Function to return maximum diagonal
# sum that are parallel to main diagonal
def maxDiagonalSum(arr, N):
# Initialize maxSum
maxSum = 0
# Traverse through the columns
for i in range(N):
# Initialize r and c
row = 0
col = i
# Diagonal sums
sum1 = 0
sum2 = 0
while col < N and row < N:
sum1 += arr[row][col]
sum2 += arr[col][row]
row += 1
col += 1
# Update maxSum with
# the maximum sum
maxSum = max([ sum1, maxSum, sum2])
# Return the maxSum
return maxSum
# Driver Code
if __name__ == '__main__':
# Given matrix mat[][]
mat = [ [ 1, 2, 5, 7 ],
[ 2, 6, 7, 3 ],
[ 12, 3, 2, 4 ],
[ 3, 6, 9, 4 ] ]
N = len(mat)
# Function Call
print(maxDiagonalSum(mat, N))
# This code is contributed by mohit kumar 29
C#
// C# program for the
// above approach
using System;
class GFG{
// Function to return maximum
// diagonal sum that are parallel
// to main diagonal
static int maxDiagonalSum(int [,]arr,
int N)
{
// Initialize maxSum
int maxSum = 0;
// Traverse through the
// columns
for(int i = 0; i < N; i++)
{
// Initialize r and c
int row = 0, col = i;
// Diagonal sums
int sum1 = 0, sum2 = 0;
while (col < N && row < N)
{
sum1 += arr[row,col];
sum2 += arr[col,row];
row++;
col++;
}
// Update maxSum with
// the maximum sum
maxSum = Math.Max(maxSum,
Math.Max(sum1,
sum2));
}
// Return the maxSum
return maxSum;
}
// Driver code
public static void Main(String[] args)
{
// Given matrix [,]mat
int [,]mat = {{1, 2, 5, 7},
{2, 6, 7, 3},
{12, 3, 2, 4},
{3, 6, 9, 4}};
int N = mat.GetLength(0);
// Function Call
Console.WriteLine(maxDiagonalSum(mat, N));
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
// javascript program for the above approach
// Function to return maximum diagonal
// sum that are parallel to main diagonal
function maxDiagonalSum( arr, N)
{
// Initialize maxSum
let maxSum = 0;
// Traverse through the columns
for (let i = 0; i < N; i++) {
// Initialize r and c
let row = 0, col = i;
// Diagonal sums
let sum1 = 0, sum2 = 0;
while (col < N && row < N) {
sum1 += arr[row][col];
sum2 += arr[col][row];
row++;
col++;
}
// Update maxSum with
// the maximum sum
maxSum = Math.max(Math.max(sum1, maxSum), sum2 );
}
// Return the maxSum
return maxSum;
}
// Driver Code
// Given matrix mat[][]
let mat
= [[ 1, 2, 5, 7 ],
[ 2, 6, 7, 3 ],
[ 12, 3, 2, 4 ],
[ 3, 6, 9, 4 ]];
let N = mat[0].length;
// Function Call
document.write(maxDiagonalSum(mat, N));
// This code is contributed by todaysgaurav
</script>
Time Complexity: O(N2)
Auxiliary Space: O(N2)
Traverse diagonals and find maximum sum:
Approach:
This approach involves traversing all diagonals of the matrix and finding the sum of elements in each diagonal. The maximum sum is then returned as the answer.
Initialize max_sum variable to 0.
Traverse through each element of the matrix.
For each element, check if it is present in the diagonal that goes from top-left to bottom-right. If it is present, add it to sum1.
Similarly, for each element, check if it is present in the diagonal that goes from top-right to bottom-left. If it is present, add it to sum2.
After calculating the sum for both diagonals, take the maximum of sum1, sum2, and max_sum and update the value of max_sum.
Finally, return the max_sum as the output.
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
int max_sum_diagonal(const vector<vector<int>>& mat) {
int max_sum = 2;
int n = mat.size();
for (int i = 0; i < n; i++) {
int sum1 = 1;
int sum2 = 11;
for (int j = 0; j < n; j++) {
// Check diagonal from top-left to bottom-right
if (i == j) {
sum1 += mat[i][j];
}
// Check diagonal from top-right to bottom-left
if (i + j == n - 1) {
sum2 += mat[i][j];
}
}
max_sum = max(max_sum, max(sum1, sum2));
}
return max_sum;
}
int main() {
vector<vector<int>> mat = {{5, 2, 5, 7}, {2, 5, 7, 3}, {12, 3, 5, 4}, {3, 6, 9, 5}};
// Output
cout << max_sum_diagonal(mat) << endl; // Output: 18
return 0;
}
// This code is contributed by Vaibhav nandan
Java
// Java program for the above approach
import java.util.*;
public class GFG {
public static int maxSumDiagonal(int[][] mat) {
int maxSum = 2;
int n = mat.length;
for (int i = 0; i < n; i++) {
int sum1 = 1;
int sum2 = 11;
for (int j = 0; j < n; j++) {
// Check diagonal from top-left to bottom-right
if (i == j) {
sum1 += mat[i][j];
}
// Check diagonal from top-right to bottom-left
if (i + j == n - 1) {
sum2 += mat[i][j];
}
}
maxSum = Math.max(maxSum, Math.max(sum1, sum2));
}
return maxSum;
}
public static void main(String[] args) {
int[][] mat = { { 5, 2, 5, 7 }, { 2, 5, 7, 3 }, { 12, 3, 5, 4 }, { 3, 6, 9, 5 } };
// Output
System.out.println(maxSumDiagonal(mat)); // Output: 18
}
}
// This code is contributed by Veena Mishra
Python3
def max_sum_diagonal(mat):
max_sum = 2
for i in range(len(mat)):
sum1 = 1
sum2 = 11
for j in range(len(mat)):
# Check diagonal from top-left to bottom-right
if i == j:
sum1 += mat[i][j]
# Check diagonal from top-right to bottom-left
if i + j == len(mat) - 1:
sum2 += mat[i][j]
max_sum = max(max_sum, sum1, sum2)
return max_sum
# Sample Input
mat = [[5, 2, 5, 7], [2, 5, 7, 3], [12, 3, 5, 4], [3, 6, 9, 5]]
# Output
print(max_sum_diagonal(mat)) # Output: 18
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the maximum sum of two diagonals in a square matrix
static int MaxSumDiagonal(List<List<int>> mat)
{
int maxSum = 2;
int n = mat.Count;
// Loop through each row of the matrix
for (int i = 0; i < n; i++)
{
int sum1 = 1; // Initialize the sum of the diagonal from top-left to bottom-right
int sum2 = 11; // Initialize the sum of the diagonal from top-right to bottom-left
// Loop through each element of the current row
for (int j = 0; j < n; j++)
{
// Check if the current element is on the top-left to bottom-right diagonal
if (i == j)
{
sum1 += mat[i][j];
}
// Check if the current element is on the top-right to bottom-left diagonal
if (i + j == n - 1)
{
sum2 += mat[i][j];
}
}
// Calculate the maximum between the two sums and update maxSum accordingly
maxSum = Math.Max(maxSum, Math.Max(sum1, sum2));
}
return maxSum;
}
//Driver Code
static void Main()
{
// Create a sample square matrix
List<List<int>> mat = new List<List<int>>
{
new List<int> {5, 2, 5, 7},
new List<int> {2, 5, 7, 3},
new List<int> {12, 3, 5, 4},
new List<int> {3, 6, 9, 5}
};
// Output the result
Console.WriteLine(MaxSumDiagonal(mat)); // Output: 18
}
}
JavaScript
function maxSumDiagonal(mat) {
let maxSum = 2;
const n = mat.length;
for (let i = 0; i < n; i++) {
let sum1 = 1;
let sum2 = 11;
for (let j = 0; j < n; j++) {
// Check diagonal from top-left to bottom-right
if (i === j) {
sum1 += mat[i][j];
}
// Check diagonal from top-right to bottom-left
if (i + j === n - 1) {
sum2 += mat[i][j];
}
}
maxSum = Math.max(maxSum, Math.max(sum1, sum2));
}
return maxSum;
}
const mat = [
[5, 2, 5, 7],
[2, 5, 7, 3],
[12, 3, 5, 4],
[3, 6, 9, 5]
];
// Output
console.log(maxSumDiagonal(mat)); // Output: 18
Time Complexity: O(n^2) where n is the size of the matrix.
Auxiliary Space: O(1)
Similar Reads
Print all the sub diagonal elements of the given square matrix
Given a square matrix mat[][] of size n * n. The task is to print all the elements which lie on the sub-diagonal of the given matrix.Examples: Input: mat[][] = { {1, 2, 3}, {3, 3, 4, }, {2, 4, 6}} Output: 3 4Input: mat[][] = { {1, 2, 3, 4}, {3, 3, 4, 4}, {2, 4, 6, 3}, {1, 1, 1, 3}} Output: 3 4 1 Rec
7 min read
Maximum difference of sum of elements in two rows in a matrix
Given a matrix of m*n order, the task is to find the maximum difference between two rows Rj and Ri such that i < j, i.e., we need to find maximum value of sum(Rj) - sum(Ri) such that row i is above row j. Examples: Input : mat[5][4] = {{-1, 2, 3, 4}, {5, 3, -2, 1}, {6, 7, 2, -3}, {2, 9, 1, 4}, {2
10 min read
Modify a matrix by replacing each element with the maximum of its left or right diagonal sum
Given a matrix mat[][] with dimensions M * N, the task is to replace each matrix elements with the maximum sum of its left or right diagonal. Examples: Input: mat[][] = {{5, 2, 1}, {7, 2, 6}, {3, 1, 9}}Output: 16 9 6 9 16 86 8 16Explanation:Replace each element with max(sum of right diagonal, sum of
7 min read
Print all the super diagonal elements of the given square matrix
Given a square matrix mat[][] of size n * n. The task is to print all the elements which lie on the super-diagonal of the given matrix.Examples: Input: mat[][] = { {1, 2, 3}, {3, 3, 4, }, {2, 4, 6}} Output: 2 4Input: mat[][] = { {1, 2, 3, 4}, {3, 3, 4, 4}, {2, 4, 6, 3}, {1, 1, 1, 3}} Output: 2 4 3 A
4 min read
Minimum sum of all absolute differences of same column elements in adjacent rows in a given Matrix
Given a matrix mat[][] having N rows and M columns, the task is to find the minimum distance between two adjacent rows where the distance between two rows is defined as the sum of all absolute differences between two elements present at the same column in the two rows. Examples: Input: mat[][] = {{1
5 min read
Find the maximum sum of diagonals for each cell of the Matrix
Given a matrix arr[][] of size N * M, the task is to find the maximum sum of diagonals for each cell of the matrix including that particular element also. Examples: Input: N = 4, M = 41 2 2 12 4 2 42 2 3 12 4 2 4Output: 20Explanation: For this example the maximum sum can be achieved by considering s
15+ min read
Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
Given a matrix of order NxN, the task is to find the minimum number of steps to convert given matrix into Diagonally Dominant Matrix. In each step, the only operation allowed is to decrease or increase any element by 1.Examples: Input: mat[][] = {{3, 2, 4}, {1, 4, 4}, {2, 3, 4}} Output: 5 Sum of the
6 min read
Minimum number of 1s present in a submatrix of given dimensions in a Binary Matrix
Given a 2D binary matrix mat[][] of size N Ã M and two integers A, B, the task is to find the least number of 1s present in a submatrix of dimensions A Ã B or B Ã A. Examples: Input: mat[][] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}} A = 2, B = 1Output: 2Explanation: Any submatrix of size 2 X 1 or 1 X 2 wi
13 min read
Finding the maximum square sub-matrix with all equal elements
Given a N x N matrix, determine the maximum K such that K x K is a submatrix with all equal elements i.e., all the elements in this submatrix must be same. Constraints: 1 <= N <= 1000 0 <= Ai , j <= 109 Examples: Input : a[][] = {{2, 3, 3}, {2, 3, 3}, {2, 2, 2}} Output : 2 Explanation
10 min read
Program to find the maximum element in a Matrix
Given an NxM matrix. The task is to find the maximum element in this matrix. Examples: Input: mat[4][4] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; Output: 25 Input: mat[3][4] = {{9, 8, 7, 6}, {5, 4, 3, 2}, {1, 0, 12, 45}}; Output: 45 Approach: The idea is to traverse the mat
6 min read