#598

Range Addition II

Easy
ArrayMathArrayMath
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(k)
Space
O(1)
O(1)
💡

Intuition

Time O(k)Space O(1)

Instead of modifying the matrix, we can track the minimum dimensions affected by all operations. The maximum integer will be determined by the smallest dimensions, and we can calculate the count directly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize min_row and min_col to m and n respectively.
  2. 2Step 2: For each operation in ops, update min_row and min_col to the minimum of their current values and the operation's dimensions.
  3. 3Step 3: The maximum integer in the matrix is the number of operations applied, which is equal to the product of min_row and min_col.
solution.py8 lines
1def maxCount(m, n, ops):
2    if not ops:
3        return m * n
4    min_row, min_col = m, n
5    for a, b in ops:
6        min_row = min(min_row, a)
7        min_col = min(min_col, b)
8    return min_row * min_col

Complexity note: The time complexity is O(k) where k is the number of operations, which is efficient compared to the brute-force approach.

  • 1The maximum integer in the matrix is determined by the smallest dimensions affected by all operations.
  • 2If no operations are performed, the entire matrix is filled with zeros.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.