Compute the maximum value inside every 3×3 submatrix of a square grid.
Largest Local Values in a Matrix
Given an integer matrix grid, consider every contiguous submatrix.
For each such submatrix, find the largest value inside it. Return a new matrix containing these maxima, where the value at position (i, j) corresponds to the maximum value in the 3 × 3 block whose top-left corner is (i, j).
The resulting matrix will have size .
Solve this by examining all valid 3×3 neighborhoods and producing their local maximums.
Input Format
gridis an integer matrixn >= 3- Each output cell corresponds to one contiguous
3 × 3submatrix ofgrid
Output Format
- Return a matrix of size
ans[i][j]is the maximum element ingrid[i..i+2][j..j+2]
Constraints
- Elements may be any integers that fit in a standard 32-bit signed integer
- Time complexity around is expected
Example 1
Input
grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]
Output
[[9,9],[8,6]]
Explanation
The top-left 3×3 block has maximum 9. The top-right block also has maximum 9. The bottom-left block has maximum 8, and the bottom-right block has maximum 6.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.