Skip to content
Problem 598 · LeetCode 598(opens in a new tab)

Range Addition II

EasyArrays

You start with an m by n grid of zeros. Each operation [a, b] in ops adds 1 to every cell in the top-left corner made of the first a rows and the first b columns.

After every operation has run, find the largest value in the grid and return how many cells hold it.

Example 1

Input:  m = 4, n = 5, ops = [[3, 4], [2, 5]]
Output: 8
Why:    the top 2 rows and left 4 columns were hit twice
2 more examples and the constraints

Example 2

Input:  m = 2, n = 6, ops = []
Output: 12
Why:    no operations, so all 12 zeros tie for the maximum

Example 3

Input:  m = 5, n = 5, ops = [[4, 1], [2, 3], [5, 5]]
Output: 2
Why:    only rows 0 to 1 of column 0 got all three

Constraints

  • 1 ≤ m, n ≤ 40,000
  • 0 ≤ number of operations ≤ 10,000
  • Each operation [a, b] has 1 ≤ a ≤ m and 1 ≤ b ≤ n

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Simulate the gridO(k·m·n)
  2. Smallest cornerO(k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 40,000 × 40,000 grid and 10,000 operationsVerdict
Simulate the gridO(k·m·n)
Runs out of memory and time
Smallest cornerO(k)
Best; one pass, two numbers

m and n are the grid's size, k is the number of operations.

Edge cases to test

  • No operations. m = 2, n = 6, ops = [] gives 12: every cell is 0, and they all tie.
  • An operation covers the whole grid. It changes nothing about which cells tie, since it adds 1 to all of them.
  • A thin operation. [4, 1] limits the answer to one column, however wide the other operations are.
  • Large grid. m = n = 40,000 with no operations gives 1,600,000,000, which still fits in a 32-bit int.

Common mistakes

  • Starting rows and cols at 0, so an empty ops list returns 0 instead of m × n.
  • Building the grid, which cannot fit in memory at the largest size.
  • Taking the max of the a's instead of the min: the maximum lives where all corners overlap.

How to talk through it

  1. 1Clarify. Can ops be empty? Do all operations start at the top-left cell?
  2. 2Give the brute force. Simulate the grid and count the maximum; say why 1.6 billion cells is too much.
  3. 3Spot the overlap. Every corner contains (0, 0), so the maximum is the number of ops, held where all corners overlap.
  4. 4Code the minimums. Track min a and min b in one loop, starting from m and n.
  5. 5Test out loud. Run the empty ops case and a case with one thin operation before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?