Minimum area such that all submatrix of the size have same maximum value
Given an N*M matrix Mat[][] containing all distinct integers, the task is to find the minimum area of the matrix (r*c, where 1 ≤ r ≤ N and 1 ≤ c ≤ M ) for every submatrix of size r*c the maximum value remains the same.
Examples:
Input: N = 4, M = 4, Mat[][] = {{9, 12, 6, 11}, {3, 15, 19, 4}, {1, 13, 8, 11}, {14, 7, 9, 15}}
Output: 3, 3
Explanation: The minimum size of the submatrix is 3*3.
All submatrix below that size does not contain the maximum 19.Input: N = 1, M = 1, Mat[][] = {{25}}
Output: 1, 1
Approach: To solve the problem follow the below idea:
There can only be one maximum element in the matrix as all the elements are unique.
So all the submatrices must contain that element.
Say the position of the maximum is (i, j).
- If the row size of the matrix is less than (i+1), there can be a submatrix starting at 0th row which will not contain the maximum.
- Also if it has less than (N – i) rows, the submatrix starting from last row will not contain the maximum.
- So the row size will be the maximum between (i + 1) and (N – i).
- Similarly, the column size will be the maximum between (j + 1) and (M – j).
Follow the steps mentioned below to implement the idea:
- Run a nested loop and traverse the whole matrix to find the maximum element of the matrix.
- Store the location of the maximum element.
- Use the above observation to find the size of the submatrix.
Below is the implementation of the above approach:
C++
// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std;#define MAX 1000 // Find M and N for which in every N*M// area the max element remains samepair<int, int> findMinArea(int Mat[][MAX], int N, int M){ // Initialize the variable int r, c; int Max = INT_MIN; // Find position of maximum element // from the grid for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (Mat[i][j] > Max) { Max = Mat[i][j]; r = i; c = j; } } } // Return minimum value of submatrix return make_pair(max(r + 1, N - r), max(c + 1, M - c));} // Driver Codeint main(){ int N = 4, M = 4; int Mat[][MAX] = { { 9, 12, 6, 11 }, { 3, 15, 19, 4 }, { 1, 13, 8, 11 }, { 14, 7, 9, 15 } }; // Function call pair<int, int> X = findMinArea(Mat, N, M); cout << X.first << " " << X.second << endl; return 0;} |
3 3
Time Complexity: O(N * M)
Auxiliary Space: O(1)



