VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-hour-glass-matrix/

⇱ Maximum sum of hour glass in matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum of hour glass in matrix

Last Updated : 30 Jul, 2025

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 1

Input : 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:

  1. Check if the matrix dimensions are at least 3×3 to fit an hourglass. If not, return -1.
  2. Iterate through the matrix, stopping 3 rows and 3 columns before the end.
  3. At each position, sum the 7 cells forming the hourglass pattern (top row, middle element, bottom row).
  4. Compare the current sum with the maximum sum found so far and update if needed.

Output
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)

Comment
Article Tags:
Article Tags: