Maximum Sum of Hourglass in Matrix

Last Updated : 22 Jul, 2026

Given a 2D matrix mat[][] of size n x m, find the maximum sum of an hourglass. An hourglass consists of seven elements in the following form:

2056958523

Return -1 if no hourglass can be formed.

Examples:

Input: mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: 35
Explanation:
The only possible hourglass is:
1 2 3
5
7 8 9
Its sum is: 1 + 2 + 3 + 5 + 7 + 8 + 9 = 35

Input: mat[][] = [[1, 2, 3], [4, 5, 6]]
Output: -1
Explanation: The matrix has fewer than 3 rows, so no hourglass can be formed.

Try It Yourself
redirect icon

Traverse All Possible Hourglasses - O(n × m) Time and O(1) Space

The key observation is that an hourglass always covers a fixed 3 × 3 region and contains exactly 7 elements. Therefore, we can treat every 3 × 3 submatrix as a possible hourglass.

Start from the top-left corner of the matrix and move the 3 × 3 window one cell at a time. For each position, calculate the sum of the 7 hourglass elements and update the maximum sum. After checking all possible positions, the maximum sum obtained is the answer.

If the matrix has fewer than 3 rows or 3 columns, no 3 × 3 submatrix exists, so return -1.

  • If n < 3 or m < 3, return -1.
  • Traverse every possible top-left corner of a 3 × 3 submatrix.
  • Compute the sum of the corresponding 7 hourglass elements.
  • Update the maximum hourglass sum.
  • Return the maximum sum.
C++
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
using namespace std;

int maxHourglass(vector<vector<int>>& mat) {
    int n = mat.size();
    int m = mat[0].size();

    if (n < 3 || m < 3) {
        return -1;
    }

    int res = INT_MIN;

    // Consider every possible top-left position of an hourglass.
    for (int i = 0; i <= n - 3; i++) {
        for (int j = 0; j <= m - 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];

            res = max(res, sum);
        }
    }

    return res;
}

int main() {
    vector<vector<int>> mat1 = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    vector<vector<int>> mat2 = {
        {1, 2, 3},
        {4, 5, 6}
    };

    cout << maxHourglass(mat1) << "\n";
    cout << maxHourglass(mat2) << "\n";

    return 0;
}
Java
public class GFG {
    public static int maxHourglass(int[][] mat) {
        int n = mat.length;
        int m = mat[0].length;

        if (n < 3 || m < 3) {
            return -1;
        }

        int res = Integer.MIN_VALUE;

        // Consider every possible top-left position of an hourglass.
        for (int i = 0; i <= n - 3; i++) {
            for (int j = 0; j <= m - 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];

                res = Math.max(res, sum);
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[][] mat1 = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        int[][] mat2 = {
            {1, 2, 3},
            {4, 5, 6}
        };

        System.out.println(maxHourglass(mat1));
        System.out.println(maxHourglass(mat2));
    }
}
Python
def maxHourglass(mat):
    n = len(mat)
    m = len(mat[0])

    if n < 3 or m < 3:
        return -1

    res = float("-inf")

    # Consider every possible top-left position of an hourglass.
    for i in range(n - 2):
        for j in range(m - 2):
            total = (
                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]
            )

            res = max(res, total)

    return res


if __name__ == "__main__":
    mat1 = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]

    mat2 = [
        [1, 2, 3],
        [4, 5, 6]
    ]

    print(maxHourglass(mat1))
    print(maxHourglass(mat2))
C#
using System;

class GFG
{
    public static int maxHourglass(int[,] mat)
    {
        int n = mat.GetLength(0);
        int m = mat.GetLength(1);

        if (n < 3 || m < 3)
        {
            return -1;
        }

        int res = int.MinValue;

        // Consider every possible top-left position of an hourglass.
        for (int i = 0; i <= n - 3; i++)
        {
            for (int j = 0; j <= m - 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];

                res = Math.Max(res, sum);
            }
        }

        return res;
    }

    public static void Main()
    {
        int[,] mat1 = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        int[,] mat2 = {
            {1, 2, 3},
            {4, 5, 6}
        };

        Console.WriteLine(maxHourglass(mat1));
        Console.WriteLine(maxHourglass(mat2));
    }
}
JavaScript
function maxHourglass(mat) {
    const n = mat.length;
    const m = mat[0].length;

    if (n < 3 || m < 3) {
        return -1;
    }

    let res = -Infinity;

    // Consider every possible top-left position of an hourglass.
    for (let i = 0; i <= n - 3; i++) {
        for (let j = 0; j <= m - 3; j++) {
            const 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];

            res = Math.max(res, sum);
        }
    }

    return res;
}

// Driver Code
const mat1 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

const mat2 = [
    [1, 2, 3],
    [4, 5, 6]
];

console.log(maxHourglass(mat1));
console.log(maxHourglass(mat2));

Output
35
-1
Comment