Max Increase to Keep City Skyline - Problem

There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.

A city's skyline is the outer contour formed by all the buildings when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.

We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.

Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.

Input & Output

Example 1 — Basic 2x2 Grid
$ Input: grid = [[3,0],[2,4]]
Output: 4
💡 Note: Row maximums: [3,4], Column maximums: [3,4]. Building at (0,1) can increase from 0 to 3 (+3), building at (1,0) can increase from 2 to 3 (+1). Total: 3+1 = 4.
Example 2 — Larger Grid
$ Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
Output: 0
💡 Note: All buildings have height 0, so row and column maximums are all 0. No increases possible while maintaining skyline.
Example 3 — Mixed Heights
$ Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: 9
💡 Note: Row maximums: [3,6,9], Column maximums: [7,8,9]. Each building can increase to min of its row/column limits.

Constraints

  • n == grid.length
  • n == grid[i].length
  • 1 ≤ n ≤ 50
  • 0 ≤ grid[i][j] ≤ 100

Visualization

Tap to expand
Max Increase to Keep City Skyline3024Original Heightsmax:3max:4max:3max:4Row/Col Limits3334After IncreasesSkyline constraints: Row max = [3,4], Column max = [3,4]Increases: +0, +3, +1, +0 = Total: 4
Understanding the Visualization
1
Input Grid
2D matrix representing building heights
2
Skyline Limits
Row and column maximums define height constraints
3
Optimal Heights
Each building can grow to min(row_max, col_max)
Key Takeaway
🎯 Key Insight: Each building's maximum height is constrained by the minimum of its row and column skyline limits
Asked in
Google 25 Microsoft 18 Amazon 15 Facebook 12
35.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen