LeetCode 2428: Maximum Sum of an Hourglass Solution

Master LeetCode problem 2428 (Maximum Sum of an Hourglass), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2428. Maximum Sum of an Hourglass

Problem Explanation

Explanation:

To find the maximum sum of an hourglass in the matrix, we can iterate through all possible hourglass positions and calculate their sum. We need to consider the constraints that the hourglass shape has and ensure it remains within the bounds of the matrix. By calculating the sum of each hourglass, we can keep track of the maximum sum encountered.

  1. Iterate through each cell in the matrix.
  2. For each cell, check if it is the top-left cell of a valid hourglass.
  3. If it is, calculate the sum of the hourglass.
  4. Update the maximum sum if the current hourglass sum is greater.
  5. Continue this process for all cells in the matrix.
  6. Return the maximum sum found.

Time Complexity: O(m * n) where m is the number of rows and n is the number of columns in the matrix. Space Complexity: O(1)

:

Solution Code

class Solution {
    public int maxHourglassSum(int[][] grid) {
        int maxSum = Integer.MIN_VALUE;
        int rows = grid.length;
        int cols = grid[0].length;

        for (int i = 0; i < rows - 2; i++) {
            for (int j = 0; j < cols - 2; j++) {
                int currentSum = 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];
                maxSum = Math.max(maxSum, currentSum);
            }
        }

        return maxSum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2428 (Maximum Sum of an Hourglass)?

This page provides optimized solutions for LeetCode problem 2428 (Maximum Sum of an Hourglass) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2428 (Maximum Sum of an Hourglass)?

The time complexity for LeetCode 2428 (Maximum Sum of an Hourglass) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2428 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2428 in Java, C++, or Python.

Back to LeetCode Solutions