Leetcode 2373. Largest Local Values in a Matrix
You are given an n x n
integer matrix grid
. Generate an n-2 x n-2
matrix result
such that:
result[i][j]
is equal to the largest value in the 3x3 matrix centered at (i+1, j+1)
in the input matrix 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]]
3 <= n <= 100
. This ensures the grid is large enough to form at least one 3x3 matrix.-10^5
to 10^5
.int
can handle the range specified.grid
such that at each point [i][j]
, we consider the 3x3 matrix centered around [i+1][j+1]
.n-2 x n-2
in size.public class Solution {
public int[][] largestLocal(int[][] grid) {
int n = grid.length;
int[][] result = new int[n - 2][n - 2];
for (int i = 0; i < n - 2; i++) {
for (int j = 0; j < n - 2; j++) {
result[i][j] = getMaxFrom3x3(grid, i, j);
}
}
return result;
}
private int getMaxFrom3x3(int[][] grid, int row, int col) {
int max = Integer.MIN_VALUE;
for (int i = row; i < row + 3; i++) {
for (int j = col; j < col + 3; j++) {
if (grid[i][j] > max) {
max = grid[i][j];
}
}
}
return max;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] grid = {
{9, 9, 8, 1},
{5, 6, 2, 6},
{8, 2, 6, 4},
{6, 2, 2, 2}
};
int[][] result = solution.largestLocal(grid);
for (int[] row : result) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
O((n-2)^2)
times.O(1)
as it considers exactly 9 elements.Therefore, the overall time complexity is O((n-2)^2).
This approach is efficient given the problem constraints and should perform well within typical input size limits.
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?