Professional Documents
Culture Documents
L21 - Maximum Sum of Hour Glass in Matrix
L21 - Maximum Sum of Hour Glass in Matrix
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
XXX
X
XXX
Maximum sum of hourglass in matrix
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