![]() |
VOOZH | about |
Given a 2D matrix, the task is to find the maximum sum of an hourglass.
An hour glass is made of 7 cells in following form.
t u v
x
x y z
Examples:
Input : mat[][] = [[1, 1, 1, 0, 0],
[0, 1, 0, 0, 0],
[1, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
Output : 7
Explanation: Below is the hour glass with maximum sum:
1 1 1
1
1 1 1Input : mat[][] = [[0, 3, 0, 0, 0],
[0, 1, 0, 0, 0],
[1, 1, 1, 0, 0],
[0, 0, 2, 4, 4],
[0, 0, 0, 2, 4]]
Output : 11
Explanation: Below is the hour glass with maximum sum:
1 0 0
4
0 2 4
Approach:
The idea is to traverse through the entire matrix and check each possible position where a complete hourglass pattern is possible.
If we count the total number of hourglasses in a matrix of size R x C, we can say that the count is equal to the count of possible top left cells in an hourglass. The number of top-left cells in an hourglass is equal to (R-2)*(C-2). Therefore, in a matrix total number of an hourglass is (R-2)*(C-2).
mat[][] = 2 3 0 0 0
0 1 0 0 0
1 1 1 0 0
0 0 2 4 4
0 0 0 2 0
Possible hour glass are :
2 3 0 3 0 0 0 0 0
1 0 0
1 1 1 1 1 0 1 0 0
0 1 0 1 0 0 0 0 0
1 1 0
0 0 2 0 2 4 2 4 4
1 1 1 1 1 0 1 0 0
0 2 4
0 0 0 0 0 2 0 2 0
Step by step approach:
7
Time complexity: O(n*m), where n is the number of rows and m is the number of columns in the matrix.
Auxiliary Space: O(1)