Skip to main content
Back to problems
#2428
Medium Algorithms

Maximum sum of an hourglass

Array Matrix Prefix Sum
76.4% acceptance
Feb 25, 2026
494
72
You are given an m x n integer matrix grid. We define an hourglass as a part of the matrix with the following form: a b c d e f g Return the maximum sum of the elements of an hourglass. Note that an hourglass cannot be rotated and must be entirely contained within the matrix.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_sum(grid: Vec<Vec<i32>>) -> i32 {
    let m = grid.len();
    let n = grid[0].len();
    let mut ans = i32::MIN;
    for i in 0..m - 2 {
      for j in 0..n - 2 {
        let s = grid[i][j] + grid[i][j + 1] + grid[i][j + 2]
          + grid[i + 1][j + 1]
          + grid[i + 2][j] + grid[i + 2][j + 1] + grid[i + 2][j + 2];
        ans = ans.max(s);
      }
    }
    ans
  }
}