Leetcode 2373. Largest Local Values in a Matrix
Given a grid of size n x n, a local value in a 3 x 3 block is defined as the maximum value in that 3 x 3 block. If there are multiple maximum values, any one may be chosen (since they are all equal).
You are tasked with finding the largest local values in each 3 x 3 block starting from the top-left of the grid. The result should be an (n-2) x (n-2) matrix where each element is the largest local value within the 3 x 3 block that starts from the same position in the original grid.
Example:
Input: grid =
[[9,9,8,1],
[5,6,2,6],
[8,2,6,4],
[6,2,2,2]]
Output:
[[9,9],
[8,6]]
Constraints:
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> largestLocal(vector<vector<int>>& grid) {
int n = grid.size();
vector<vector<int>> result(n - 2, vector<int>(n - 2));
for (int i = 0; i < n - 2; ++i) {
for (int j = 0; j < n - 2; ++j) {
int max_val = 0;
for (int k = i; k < i + 3; ++k) {
for (int l = j; l < j + 3; ++l) {
max_val = max(max_val, grid[k][l]);
}
}
result[i][j] = max_val;
}
}
return result;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?