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
ai
andbi
. - Therefore, find the minimum
ai
andbi
from 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)
, wherep
is the number of operations inops
. This is because we iterate through theops
array to determine the minimumai
andbi
. - Space:
O(1)
, as we only use a constant amount of additional space.