Range Addition 2
EasyUpdated: Aug 2, 2025
Practice on:
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:
Input: m = 3, n = 3, ops = [[2,2],[3,3]]
Output: 4
Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.
Example 2:
Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]
Output: 4
Example 3:
Input: m = 3, n = 3, ops = []
Output: 9
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
Java
public class Solution {
public int maxCount(int m, int n, int[][] ops) {
int minA = m;
int minB = n;
for (int[] op : ops) {
minA = Math.min(minA, op[0]);
minB = Math.min(minB, op[1]);
}
return minA * minB;
}
}
Python
class Solution:
def maxCount(self, m, n, ops):
min_a = m
min_b = n
for op in ops:
min_a = min(min_a, op[0])
min_b = min(min_b, op[1])
return min_a * min_b
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.