Leetcode 598. Range Addition II
Given an m x n matrix M initialized with all 0’s and several update operations.
Operations are represented by a 2D array, where each operation is represented by an array with two positive integers a and b, which means M[i][j] should be incremented by 1 for all 0 <= i < a and 0 <= j < b.
You need to return the count of the maximum integer in the matrix after performing all the operations.
Example:
Input: m = 3, n = 3, ops = [[2,2],[3,3]]
Output: 4
Explanation:
Initially, the M =
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
After performing [2,2], the matrix M is:
[[1, 1, 0],
[1, 1, 0],
[0, 0, 0]]
After performing [3,3], the matrix M is:
[[2, 2, 1],
[2, 2, 1],
[1, 1, 1]]
The largest integers in M are 2, and there are four of them in M. So return 4.
Constraints:
1 <= m, n <= 4 * 10^40 <= ops.length <= 10^4ops[i].length == 21 <= ai <= m1 <= bi <= nAssuming the answers:
Instead of directly simulating the operations on the matrix, which could become computationally expensive (especially for large values of m and n), we can determine the region that is incremented the most number of times.
Each operation updates a submatrix from (0,0) to (a,b). The submatrix with the most updates will be the smallest (a, b) across all operations. Thus, all we need to do is find the minimum a and b across all operations.
min_a to m and min_b to n.min_a and min_b with the minimum values of a and b respectively.min_a * min_b.The time complexity for iterating over the operations is O(k) where k is the number of operations. Space complexity is O(1) as we only maintain a few variables.
#include <vector>
#include <algorithm>
class Solution {
public:
int maxCount(int m, int n, std::vector<std::vector<int>>& ops) {
int minA = m;
int minB = n;
for (const auto& op : ops) {
minA = std::min(minA, op[0]);
minB = std::min(minB, op[1]);
}
return minA * minB;
}
};
This code effectively captures the essence of determining the maximum impacted area after all operations and computes it in an efficient manner.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?