The Indian Engineer

Problem 2373 Largest Local Values in a Matrix

Posted on 4 mins

Matrix 2D-Array Cpp Vector

Problem Statement

Link - Problem 2373

Question

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.

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

Solution

class Solution {
public:
    vector<vector<int>> largestLocal(vector<vector<int>>& grid) {
        vector<vector<int>>ans(grid.size()-2,vector<int>(grid[0].size()-2));
        int locMax = INT_MIN;
        for(int row = 0; row < grid.size()-2; row++)
        {
            for(int col = 0; col < grid[0].size()-2; col++)
            {
                for(int i = row; i<row+3; i++)
                {
                    for(int j = col; j<col+3; j++)
                        locMax = max(locMax,grid[i][j]);
                }
                ans[row][col] = locMax;
                locMax = INT_MIN;
            }
        }
        return ans;
    }
};

Complexity Analysis

Explanation

1. Intuition

2. Implementation

Intresting fact

This problem closely simulates a very powerful ML algorithm in CNNs called as Max Pooling. Max pooling is a sample-based discretization process. The objective is to down-sample an input representation (image, hidden-layer output matrix, etc.), reducing its dimensionality and allowing for assumptions to be made about features contained in the sub-regions binned.

Key terms in Max Pooling:

placeholder


This problem simulates Max pooling. This shows a real world application of a DSA problem.