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 the 3 x 3
matrix in grid
centered around row i + 1
and column j + 1
.In other words, we want to find the largest value in every contiguous 3 x 3
matrix in grid
.
For example, given the following input:
grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]
The expected output would be:
[[9,9],[8,6]]
Another example:
grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]]
Expected output:
[[2,2,2],[2,2,2],[2,2,2]]
Write a function to solve this problem and discuss its time and space complexity. Also, discuss any potential edge cases and how your solution handles them.
The most straightforward approach is to iterate through each possible 3x3 submatrix within the given grid
and find the maximum value within that submatrix. This maximum value is then placed in the corresponding position in the maxLocal
matrix.
maxLocal
matrix with dimensions (n-2) x (n-2)
. This matrix will store the maximum values of each 3x3 submatrix.grid
matrix from i = 0
to n-2
and j = 0
to n-2
.(i, j)
position, find the maximum value in the 3x3 submatrix centered at (i+1, j+1)
.maxLocal[i][j]
.maxLocal
matrix.def max_local_brute_force(grid):
n = len(grid)
max_local = [[0] * (n - 2) for _ in range(n - 2)]
for i in range(n - 2):
for j in range(n - 2):
max_val = 0
for x in range(i, i + 3):
for y in range(j, j + 3):
max_val = max(max_val, grid[x][y])
max_local[i][j] = max_val
return max_local
maxLocal
matrix, we iterate through a 3x3 submatrix.maxLocal
matrix.This solution is essentially the same as the brute force, as there is no apparent overlapping subproblem or optimal substructure to exploit with dynamic programming. The brute force is already quite efficient. There aren't any tricks to reduce the number of iterations required.
The algorithm remains the same as the brute force approach:
maxLocal
matrix with dimensions (n-2) x (n-2)
. This matrix will store the maximum values of each 3x3 submatrix.grid
matrix from i = 0
to n-2
and j = 0
to n-2
.(i, j)
position, find the maximum value in the 3x3 submatrix centered at (i+1, j+1)
.maxLocal[i][j]
.maxLocal
matrix.def max_local_optimal(grid):
n = len(grid)
max_local = [[0] * (n - 2) for _ in range(n - 2)]
for i in range(n - 2):
for j in range(n - 2):
max_val = 0
for x in range(i, i + 3):
for y in range(j, j + 3):
max_val = max(max_val, grid[x][y])
max_local[i][j] = max_val
return max_local
maxLocal
matrix, we iterate through a 3x3 submatrix.maxLocal
matrix.3 <= n <= 100
, so we don't need to handle cases where n
is less than 3. If n
were less than 3, we could throw an exception or return an empty matrix, depending on the requirements.grid
is None
or empty, we might want to return an empty matrix or throw an exception.