Largest Local Values in a Matrix

Updated on 04 June, 2025
Largest Local Values in a Matrix header image

Problem Statement

You are provided with an n x n integer matrix named grid. Your task is to construct a new integer matrix called maxLocal of size (n - 2) x (n - 2). Each element in the maxLocal matrix, maxLocal[i][j], should represent the largest value found in the 3 x 3 submatrix of the original grid. This submatrix is centered around the element at position (i+1, j+1) in the grid. Essentially, for each cell in the maxLocal, you need to examine a 3 x 3 region in the grid and determine the maximum value within that region. Finally, return the resulting maxLocal matrix, which offers a condensed view of local maxima across the original grid.

Examples

Example 1

Input:

grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]

Output:

[[9,9],[8,6]]

Explanation:

The diagram above shows the original matrix and the generated matrix.
Notice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.

Example 2

Input:

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]]

Output:

[[2,2,2],[2,2,2],[2,2,2]]

Explanation:

Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid.

Constraints

  • n == grid.length == grid[i].length
  • 3 <= n <= 100
  • 1 <= grid[i][j] <= 100

Approach and Intuition

  1. Understanding the Output Dimensions:

    • Given the task, it's clear that for an n x n grid, the resultant matrix maxLocal will have dimensions (n-2) x (n-2). This is because the outer borders of the grid don't allow a full 3 x 3 matrix around them.
  2. Traversal Strategy:

    • You will traverse the original grid starting at row index 1 and ending at n-2 for both rows and columns. This ensures you are only considering center points for 3 x 3 matrices that fully fit inside the grid.
  3. Extracting the Local Maximum:

    • For each center at (i, j), examine the elements from the rows i-1 to i+1 and columns j-1 to j+1. Among these 3x3=9 elements, find the maximum value and assign it to maxLocal[i-1][j-1].
  4. Efficient Maximum Search:

    • It's efficient to re-check only a part of the 3x3 matrix that changes as you move to the next center over the rows or columns, especially in larger grids. This can be optimized using advanced techniques like sliding windows, but a straightforward double loop approach is simple and effective within the given constraints.
  5. Edge Cases:

    • The smallest grid you might deal with is 3x3, resulting in a 1x1 maxLocal matrix. This requires only one pass to determine the maximum in the entire grid.
    • Also, ensure to handle grids where all elements are the same or where the maximum value is at the edge of the grid.

By following this structured approach, the problem breaks down into manageable steps, where determining the local maximum becomes a series of local explorations within a confined matrix space. This method ensures that you capture the highest value from each possible 3 x 3 region as you condense the information into the resultant maxLocal matrix.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
private:
    int getMaxInSubgrid(vector<vector<int>>& matrix, int row, int col) {
        int highestValue = 0;
        for (int i = row; i < row + 3; i++) {
            for (int j = col; j < col + 3; j++) {
                highestValue = max(highestValue, matrix[i][j]);
            }
        }
        
        return highestValue;
    }
public: 
    vector<vector<int>> largestLocal(vector<vector<int>>& matrix) {
        int size = matrix.size();
        
        vector<vector<int>> result(size - 2, vector<int>(size - 2));
        for (int i = 0; i < size - 2; i++) {
            for (int j = 0; j < size - 2; j++) {
                result[i][j] = getMaxInSubgrid(matrix, i, j);
            }
        }
        
        return result;
    }
};

This solution involves determining the largest local values within 3x3 subgrids of a larger matrix using C++.

  • First, you define a helper method getMaxInSubgrid() within the Solution class to scan each 3x3 subgrid, extracting the maximum value found within this window. This method iterates over the specified rows and columns of the matrix, continuously updating the highest value found.

  • Then, in the largestLocal() method:

    1. Compute the size of the resulting matrix, which is smaller than the original matrix by 2 rows and columns because the 3x3 subgrids must fit entirely within the original matrix boundaries.
    2. Define result, a matrix with dimensions (size - 2) x (size - 2) to store the maximum values from each subgrid.
    3. Loop through the possible top-left corners of each 3x3 subgrid in the original matrix. For every possible position, invoke the getMaxInSubgrid() function to find and then store the maximum value for the current subgrid at the corresponding position in the result matrix.

This approach ensures that you effectively capture the highest value from each subgrid in the original matrix, making efficient use of nested loops to traverse and compute the required maximums. The end product is a matrix filled with local maxima as per specified parameters.

java
class Solution {
    private int getMaxIn3x3(int[][] matrix, int row, int col) {
        int largest = 0;
        for (int r = row; r < row + 3; r++) {
            for (int c = col; c < col + 3; c++) {
                largest = Math.max(largest, matrix[r][c]);
            }
        }
        
        return largest;
    }
    
    public int[][] largestInLocalArea(int[][] matrix) {
        int size = matrix.length;
        
        int[][] resultMatrix = new int[size - 2][size - 2];
        for (int i = 0; i < size - 2; i++) {
            for (int j = 0; j < size - 2; j++) {
                resultMatrix[i][j] = getMaxIn3x3(matrix, i, j);
            }
        }
        
        return resultMatrix;
    }
}

The Java solution provided outlines a method to find the largest local values in a matrix. Here's a breakdown of how the solution operates:

  • An auxiliary method named getMaxIn3x3 is defined, which extracts the maximum value from any 3x3 submatrix within the larger matrix. The method iterates over each row and column within the specified 3x3 area, updating the maximum value accordingly.

  • The primary method largestInLocalArea initializes a resultMatrix that will store the largest values from each 3x3 submatrix. The size of this matrix is (size-2) x (size-2), accounting for the boundaries of the 3x3 submatrices at the edges of the original matrix.

  • The process involves iterating through each possible top-left corner of a 3x3 submatrix in the original matrix, extracting the maximum value using getMaxIn3x3, and storing this value in the corresponding position of the resultMatrix.

  • The resulting matrix is returned, containing the maximum local values from each 3x3 section of the initial matrix.

This approach ensures efficient localization of maximum values in any given matrix, with operations concentrated on small, manageable sections, thus optimizing performance and clarity.

python
class Solution:
    def maximum_value(self, matrix, top_x, top_y):
        highest_val = 0
        for row in range(top_x, top_x + 3):
            for col in range(top_y, top_y + 3):
                highest_val = max(highest_val, matrix[row][col])
        
        return highest_val

    def largest3x3(self, matrix):
        size = len(matrix)
        
        result_matrix = [[0] * (size - 2) for _ in range(size - 2)]
        for row in range(size - 2):
            for col in range(size - 2):
                result_matrix[row][col] = self.maximum_value(matrix, row, col)
        
        return result_matrix

This Python3 solution addresses the problem of finding the largest local values within 3x3 submatrices of a given square matrix. The code is structured within a class named Solution which comprises two principal functions:

  • maximum_value(matrix, top_x, top_y):

    • This function calculates the maximum value within a 3x3 submatrix starting from the coordinates top_x and top_y within the given matrix.
    • Iterates through each element within the bounds of the 3x3 area and updates highest_val if a larger value is found.
  • largest3x3(matrix):

    • Initializes a new matrix result_matrix with reduced dimensions to store the maximum values from each 3x3 submatrix of the input matrix.
    • Iterates through the input matrix, adjusting the indices to fit the boundaries of 3x3 submatrices.
    • At each point, calls maximum_value to evaluate and store the highest value in the corresponding cell of result_matrix.

The solution employs a nested iteration strategy, effectively scanning through the matrix and computing maximums locally, which ensures every potential 3x3 section is considered. The result is stored in result_matrix where each element represents the maximum value of a specific 3x3 submatrix in the original matrix, adhering closely to the problem requirements.

Comments

No comments yet.