Problem
You are given an m x n matrix M initialized with all 0’s and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.
Count and return the number of maximum integers in the matrix after performing all the operations.
Examples
Example 1:
$$ \begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix} \implies \begin{bmatrix} \colorbox{blue} 1 & \colorbox{blue} 1 & 0 \\ \colorbox{blue} 1 & \colorbox{blue} 1 & 0 \\ 0 & 0 & 0 \end{bmatrix} \implies \begin{bmatrix} \colorbox{blue} 2 & \colorbox{blue} 2 & \colorbox{blue} 1 \\ \colorbox{blue} 2 & \colorbox{blue} 2 & \colorbox{blue} 1 \\ \colorbox{blue} 1 & \colorbox{blue} 1 & \colorbox{blue} 1 \end{bmatrix} $$
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Counting
Here is the approach:
- Each operation affects the submatrix from the top-left corner
(0, 0)to(ai-1, bi-1). - The matrix cell with the maximum value will be at the intersection of all the smallest
aiandbi. - Therefore, find the minimum
aiandbifrom all operations, which determines the dimensions of the submatrix with the maximum value. - The number of maximum integers in the matrix is the area of this submatrix.
Code
| |
| |
Complexity
- Time:
O(p), wherepis the number of operations inops. This is because we iterate through theopsarray to determine the minimumaiandbi. - Space:
O(1), as we only use a constant amount of additional space.