[LeetCode] Maximum Sum of an Hourglass

2428. Maximum Sum of an Hourglass

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.

Note that an hourglass cannot be rotated and must be entirely contained within the matrix.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int maxSum(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size();
int res = 0;
for(int i = 0; i < n - 2; i++) {
for(int j = 0; j < m - 2; j++) {
int now = A[i][j] + A[i][j+1] + A[i][j+2] + A[i+1][j+1] + A[i+2][j] + A[i+2][j+1] + A[i+2][j+2];
res = max(res, now);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/02/PS/LeetCode/maximum-sum-of-an-hourglass/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.