Largest Local Values in a Matrix - Problem
Imagine you're analyzing satellite imagery and need to identify hotspots in a grid-based map. Given an n x n integer matrix grid, your task is to find the maximum value in every possible 3x3 neighborhood.
Create a matrix maxLocal of size (n-2) x (n-2) where each element maxLocal[i][j] represents the largest value found in the 3x3 submatrix centered at position (i+1, j+1) in the original grid.
Visual Example:
Original 4x4 grid: Result 2x2 grid: [9,9,8,1] [9,9] [5,6,2,6] โ [8,6] [8,2,6,4] [6,2,2,2]
Each value in the result represents the maximum of a 3x3 region from the original matrix.
Input & Output
example_1.py โ Basic 4x4 Grid
$
Input:
grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]
โบ
Output:
[[9,9],[8,6]]
๐ก Note:
First 3x3 region (top-left): max of [9,9,8,5,6,2,8,2,6] = 9. Second 3x3 region (top-right): max of [9,8,1,6,2,6,2,6,4] = 9. Third 3x3 region (bottom-left): max of [5,6,2,8,2,6,6,2,2] = 8. Fourth 3x3 region (bottom-right): max of [6,2,6,2,6,4,2,2,2] = 6.
example_2.py โ Minimum Size Grid
$
Input:
grid = [[1,1,1],[1,1,1],[1,1,1]]
โบ
Output:
[[1]]
๐ก Note:
For a 3x3 input, we get a 1x1 output. The only 3x3 region is the entire grid, and the maximum value is 1.
example_3.py โ Larger Grid with Pattern
$
Input:
grid = [[20,8,20,6,16],[8,16,4,12,8],[20,4,20,10,12],[8,12,8,16,4],[16,8,12,4,20]]
โบ
Output:
[[20,20,16],[20,20,12],[20,16,16]]
๐ก Note:
Each position in the result corresponds to the maximum value found in the respective 3x3 region of the original 5x5 grid.
Constraints
- n == grid.length == grid[i].length
- 3 โค n โค 100
- 1 โค grid[i][j] โค 100
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Result Matrix
Create a (n-2) ร (n-2) matrix to store maximum values
2
Position Sliding Window
Place 3x3 window at each valid position (0,0) to (n-3,n-3)
3
Find Local Maximum
Scan all 9 cells in current window to find maximum value
4
Store Result
Place the maximum value in corresponding position of result matrix
Key Takeaway
๐ฏ Key Insight: By systematically scanning each valid 3ร3 region and tracking the maximum value, we can efficiently build the result matrix in O(nยฒ) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code