Problem
You are given an n x n
integer matrix grid
.
Generate an integer matrix maxLocal
of size (n - 2) x (n - 2)
such that:
maxLocal[i][j]
is equal to the largest value of the3 x 3
matrix ingrid
centered around rowi + 1
and columnj + 1
.
In other words, we want to find the largest value in every contiguous 3 x 3
matrix in grid
.
Return the generated matrix.
Examples
Example 1:
$$ Input = \begin{bmatrix} \color{red} 9 & \color{red} 9 & 8 & 1 \\ 5 & \color{red} 6 & 2 & \color{red} 6 \\ \color{red} 8 & 2 & \color{red} 6 & 4 \\ 6 & 2 & 2 & 2 \end{bmatrix} , Output = \begin{bmatrix} 9 & 9 \\ 8 & 6 \end{bmatrix} $$
|
|
Example 2:
$$ Input = \begin{bmatrix} 1 & 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 1 & \color{red} 2 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \end{bmatrix} , Output = \begin{bmatrix} 2 & 2 & 2 \\ 2 & 2 & 2 \\ 2 & 2 & 2 \end{bmatrix} $$
|
|
Solution
Method 1 - Nested Loops with sliding window of 3x3 matrix
We create the 2 nested loops - 0 to n -2…which will fill the answer array. Now, we can run nested 3x3 loop to find max we have seen so far. These last 2 loops are like a sliding window
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
- We run 2 outer loops with(n-2)x(n-2)
complexity and 2 inner loops with3x3 = 9
times the complexity. HenceO(9n^2) = O(n^2)
- 🧺 Space complexity:
O(1)