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

Max Increase to Keep City Skyline

MediumGreedy algorithms

A city is an n × n grid of blocks, and each block holds one building. grid[r][c] is the height of the building in row r, column c. A height of 0 means the block is empty.

Seen from far away on any of the four sides, the city shows a skyline: in each row (from the west or east) or column (from the north or south), you only see the tallest building. You may make any buildings taller, by any amounts, as long as none of the four skylines changes.

Return the largest possible total of all the height increases.

Example 1

Input:  grid = [[2,5,1],[4,0,3],[1,6,2]]
Output: 12
Why:    row tops 5,4,6 and column tops 4,6,3 cap every cell
2 more examples and the constraints

Example 2

Input:  grid = [[7,7],[7,7]]
Output: 0
Why:    every building already sets the skyline

Example 3

Input:  grid = [[0,0],[0,9]]
Output: 0
Why:    each zero shares a row or column whose top is 0

Constraints

  • The grid is square, with n rows and n columns
  • Every height is between 0 and 100
  • 2 ≤ n ≤ 50

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. Scan the row and column per cellO(n³)
  2. Precompute row and column maximaO(n²)

The idea in one sentence

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

Side by side

ApproachTimeCell reads for a 50 × 50 gridVerdict
Scan the row and column per cellO(n³)
Passes at n = 50, but wasteful
Precompute row and column maximaO(n²)
Best; each maximum found once

n = the side of the grid.

Edge cases to test

  • All the same height. Every building is already the top of its row and column, so nothing can grow: 0.
  • Empty blocks. A 0 can grow too, but only if both its row and its column contain something taller.
  • One tall building. In [[0,0],[0,9]], each zero has a row or column whose top is 0, so the answer is 0.
  • The largest grid. 2,500 cells, each up to 100 higher, gives a total under 250,000, which fits in an int.

Common mistakes

  • Using the larger of the two maxima, which changes the skyline from the other side.
  • Recomputing the row and column maxima after raising a building; they never change.
  • Mixing up rows and columns when filling colMax.

How to talk through it

  1. 1Clarify. Is the grid always square? Can a building of height 0 be raised?
  2. 2Describe the skyline. From the side you see each row's tallest; from the front, each column's tallest.
  3. 3Find each cell's limit. A building may rise to the smaller of those two values and no higher.
  4. 4Precompute. The maxima never change, so compute them once and make the answer one more pass: O(n²).
  5. 5Test out loud. Try an all-equal grid, which gives 0, and the 3 × 3 example.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?