Skip to content

2373. Largest Local Values in a Matrix 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  vector<vector<int>> largestLocal(vector<vector<int>>& grid) {
    const int n = grid.size();
    vector<vector<int>> ans(n - 2, vector<int>(n - 2));

    for (int i = 0; i < n - 2; ++i)
      for (int j = 0; j < n - 2; ++j)
        for (int x = i; x < i + 3; ++x)
          for (int y = j; y < j + 3; ++y)
            ans[i][j] = max(ans[i][j], grid[x][y]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int[][] largestLocal(int[][] grid) {
    final int n = grid.length;
    int[][] ans = new int[n - 2][n - 2];

    for (int i = 0; i < n - 2; ++i)
      for (int j = 0; j < n - 2; ++j)
        for (int x = i; x < i + 3; ++x)
          for (int y = j; y < j + 3; ++y)
            ans[i][j] = Math.max(ans[i][j], grid[x][y]);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def largestLocal(self, grid: list[list[int]]) -> list[list[int]]:
    n = len(grid)
    ans = [[0] * (n - 2) for _ in range(n - 2)]

    for i in range(n - 2):
      for j in range(n - 2):
        for x in range(i, i + 3):
          for y in range(j, j + 3):
            ans[i][j] = max(ans[i][j], grid[x][y])

    return ans