0% found this document useful (0 votes)
90 views7 pages

L21 - Maximum Sum of Hour Glass in Matrix

The document discusses finding the maximum sum of an hourglass shape in a matrix. It provides an example matrix, explains what constitutes an hourglass, and gives Java code to find the maximum hourglass sum by iterating through all possible hourglasses in the matrix.

Uploaded by

Siddharth Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views7 pages

L21 - Maximum Sum of Hour Glass in Matrix

The document discusses finding the maximum sum of an hourglass shape in a matrix. It provides an example matrix, explains what constitutes an hourglass, and gives Java code to find the maximum hourglass sum by iterating through all possible hourglasses in the matrix.

Uploaded by

Siddharth Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Maximum sum of

hourglass in matrix
Introduction
✔ In this problem, we are given a 2D array (matrix) of any order.

✔ Our task is to create a program that finds the maximum sum of the
hourglass.

✔ Out of all the possible hourglass sums of a given m*n ordered matrix,
we have to print the maximum of all the sums

✔ In our problem, Hourglass is a 7 element shape made in the matrix


in the following form:

XXX
X
XXX
Maximum sum of hourglass in matrix

So, an hourglass can be created using the following


Example: indexes:-

Consider the matrix:- matrix[i][j] matrix[i][j+1] matrix[i]


2400 [j+2]
0110 matrix[i+1][j+1]
4210 matrix[i+2][j] matrix[i+2][j+1]
0301 matrix[i+2][j+2]

The hourglasses are :

2 4 0 0 1 1 We will find the sum of all these elements of the


1 2 array from [0][0] to [R2][C-2] starting points. And
4 2 1 0 3 0 the find the maxSum for all these hourglasses
created from array elements.

4 0 0 1 1 0
1 1
2 1 0 3 0 1
public class HourglassSum {
static int findMaxHourglassSum(int[][] mat) {
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i <= mat.length - 3; i++) {
for (int j = 0; j <= mat[0].length - 3; j++) {
int sum = mat[i][j] + mat[i][j + 1] + mat[i][j + 2]
+ mat[i + 1][j + 1]
+ mat[i + 2][j] + mat[i + 2][j + 1] + mat[i + 2][j + 2];
maxSum = Math.max(maxSum, sum);
}
}
return maxSum;
}
public static void main(String[] args) {
int[][] mat = {
{1, 2, 3, 0, 0},
{0, 0, 0, 0, 0},
{2, 1, 4, 0, 0},
{0, 0, 0, 0, 0},
{1, 1, 0, 1, 0}
};
int result = findMaxHourglassSum(mat);
System.out.println("Maximum sum of hourglass = " + result);
}
}
Output: Maximum sum of hour glass = 13

Time complexity: O(R x C).


Auxiliary Space: O(1)
THANK YOU

You might also like