Leetcode 2428: Maximum Sum of an Hourglass

grid47
grid47
Exploring patterns and algorithms
Mar 9, 2024 5 min read

You are given a matrix of integers. An hourglass is defined as a pattern of elements in the matrix where the middle element is surrounded by 3 elements above it and 3 elements below it, forming the shape of an hourglass. Your task is to find the maximum sum of all hourglasses that can be formed within the matrix.
Problem
Approach
Steps
Complexity
Input: You are given an m x n matrix of integers.
Example: grid = [[4, 1, 2, 3], [5, 2, 1, 4], [9, 7, 1, 6], [2, 5, 8, 3]]
Constraints:
• 3 <= m, n <= 150
• 0 <= grid[i][j] <= 106
Output: Return the maximum sum of the elements of an hourglass in the matrix.
Example: Output: 30
Constraints:
• The matrix will always have at least one hourglass.
Goal: To compute the maximum sum of an hourglass in the given matrix.
Steps:
• 1. Iterate over all possible positions in the matrix where an hourglass can be formed.
• 2. For each valid position, calculate the sum of the hourglass and track the maximum sum.
• 3. Return the maximum sum found.
Goal: Ensure the solution works within the given constraints.
Steps:
• The grid will always have at least 3 rows and 3 columns.
Assumptions:
• The matrix will always have dimensions where an hourglass can be formed (at least 3x3).
• All elements in the matrix are non-negative integers.
Input: grid = [[6, 2, 1, 3], [4, 2, 1, 5], [9, 2, 8, 7], [4, 1, 2, 9]]
Explanation: The hourglass with the maximum sum is formed by the cells 6, 2, 1, 2, 9, 2, 8. The sum is 30.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus