Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2428: Maximum Sum of an Hourglass

In this guide, we solve Leetcode #2428 Maximum Sum of an Hourglass in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an m x n integer matrix grid. We define an hourglass as a part of the matrix with the following form: Return the maximum sum of the elements of an hourglass.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Matrix, Prefix Sum

Intuition

Range queries become simple once we precompute cumulative sums.

We can transform subarray conditions into prefix comparisons.

Approach

Compute prefix sums and use a map to find matching prefixes.

This avoids nested loops while keeping the logic clear.

Steps:

  • Compute prefix sums.
  • Use a map to find valid ranges.
  • Update the answer.

Example

Input: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]] Output: 30 Explanation: The cells shown above represent the hourglass with the maximum sum: 6 + 2 + 1 + 2 + 9 + 2 + 8 = 30.

Python Solution

class Solution: def maxSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) ans = 0 for i in range(1, m - 1): for j in range(1, n - 1): s = -grid[i][j - 1] - grid[i][j + 1] s += sum( grid[x][y] for x in range(i - 1, i + 2) for y in range(j - 1, j + 2) ) ans = max(ans, s) return ans

Complexity

The time complexity is O(m×n)O(m \times n)O(m×n), where mmm and nnn are the number of rows and columns of the matrix, respectively. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy