LeetCode 2428: Maximum Sum of an Hourglass
Problem Description
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.
- Iterate through each cell in the matrix.
- For each cell, check if it is the top-left cell of a valid hourglass.
- If it is, calculate the sum of the hourglass.
- Update the maximum sum if the current hourglass sum is greater.
- Continue this process for all cells in the matrix.
- 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)
:
Solutions
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;
}
}
Loading editor...