Max Increase to Keep City Skyline - Problem

๐Ÿ™๏ธ Max Increase to Keep City Skyline

Imagine you're a city planner working with a n ร— n grid of buildings, where each cell represents the height of a building. Your goal is to maximize the total height increase of all buildings while preserving the city's iconic skyline from all four cardinal directions (north, south, east, west).

The skyline constraint means that when viewed from any direction, the tallest building in each row/column must remain the same. For example, if building at position (2,3) is the tallest in row 2, it must stay the tallest even after increases.

Key Challenge: Each building can be increased up to the minimum of:

  • Maximum height in its row
  • Maximum height in its column

Return the maximum total sum that all building heights can be increased by without changing any skyline view.

Input & Output

example_1.py โ€” Basic 3x3 Grid
$ Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
โ€บ Output: 35
๐Ÿ’ก Note: Row maximums: [8,7,9,3], Column maximums: [9,4,8,7]. Each building can increase to min(row_max, col_max) for its position. Total increase = 35.
example_2.py โ€” Uniform Heights
$ Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
โ€บ Output: 0
๐Ÿ’ก Note: All buildings have height 0, and all row/column maximums are 0. No building can be increased without changing the skyline.
example_3.py โ€” Single Row Dominance
$ Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
โ€บ Output: 0
๐Ÿ’ก Note: Each building is already at its maximum possible height (equals min of its row max and column max), so no increases are possible.

Constraints

  • n == grid.length
  • n == grid[i].length
  • 1 โ‰ค n โ‰ค 50
  • 0 โ‰ค grid[i][j] โ‰ค 100

Visualization

Tap to expand
๐Ÿ™๏ธ Max City Skyline Growth3โ†’40โ†’58โ†’84โ†’7Before GrowthAfter Growth๐ŸŽฏ Key InsightEach building grows to min(row_max, col_max)preserving all four cardinal skylines!Total increase maximized while maintaining city's iconic profile
Understanding the Visualization
1
Survey Current Skylines
Identify the tallest building in each row (east-west view) and each column (north-south view)
2
Calculate Growth Limits
Each building can grow up to the minimum of its row maximum and column maximum
3
Maximize Development
Sum all possible height increases while keeping skyline constraints
Key Takeaway
๐ŸŽฏ Key Insight: Precomputing row and column maximums allows us to determine each building's growth potential in constant time, achieving optimal O(nยฒ) performance.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 5
38.2K Views
Medium Frequency
~15 min Avg. Time
1.6K 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