2428. Maximum Sum of an Hourglass ¶ Time: $O(mn)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class Solution { public: int maxSum(vector<vector<int>>& grid) { int ans = 0; for (int i = 1; i + 1 < grid.size(); ++i) for (int j = 1; j + 1 < grid[0].size(); ++j) ans = max(ans, grid[i - 1][j - 1] + grid[i - 1][j] + grid[i - 1][j + 1] + grid[i][j] + grid[i + 1][j - 1] + grid[i + 1][j] + grid[i + 1][j + 1]); return ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12public class Solution { public int maxSum(int[][] grid) { int ans = 0; for (int i = 1; i + 1 < grid.length; ++i) for (int j = 1; j + 1 < grid[0].length; ++j) ans = Math.max(ans, grid[i - 1][j - 1] + grid[i - 1][j] + grid[i - 1][j + 1] + grid[i][j] + grid[i + 1][j - 1] + grid[i + 1][j] + grid[i + 1][j + 1]); return ans; } } 1 2 3 4 5 6class Solution: def maxSum(self, grid: list[list[int]]) -> int: return max( grid[i - 1][j - 1] + grid[i - 1][j] + grid[i - 1][j + 1] + grid[i][j] + grid[i + 1][j - 1] + grid[i + 1][j] + grid[i + 1][j + 1] for i in range(1, len(grid) - 1) for j in range(1, len(grid[0]) - 1))