#2373
Easy Algorithms Largest local values in a matrix
Array Matrix
87.7% acceptance
Feb 25, 2026
1320
182
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.
Return the generated matrix.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn largest_local(grid: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let n = grid.len();
(0..n-2).map(|i| {
(0..n-2).map(|j| {
let mut mx = 0;
for di in 0..3 { for dj in 0..3 { mx = mx.max(grid[i+di][j+dj]); } }
mx
}).collect()
}).collect()
}
}