![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
3 3
Time Complexity: O(N * M)
Auxiliary Space: O(1)