Python 0807.py
class Solution:
def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
n = len(grid)
# highest building per row and column
hx = [ 0 ] * n
for y in range(n):
for x in range(n):
hx[x] = max(hx[x], grid[y][x])
hy = [ 0 ] * n
for x in range(n):
for y in range(n):
hy[y] = max(hy[y], grid[y][x])
# do not exceed the highest building in the same row and column
result = 0
for y in range(n):
for x in range(n):
limit = min(hx[x], hy[y])
result += limit - grid[y][x]
return result
Difficulty
and has an acceptance rate of about 87% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “maximum increase keeping skyline” problem. It receives a square matrix grid that represents building heights on a city map. The goal is to compute the total sum by which the heights can be increased without altering the skyline when viewed from any of the four cardinal directions. The algorithm proceeds in three logical phases: determining the tallest building in each column, determining the tallest building in each row, and finally aggregating the permissible height increments for every cell.
Key Steps
Determining the tallest building per column
The first loop iterates over every row and column, updating an array that stores the maximum height observed in each column. The array hx is initialized with zeros and indexed by column position. For each cell (y, x), the current column maximum hx[x] is replaced by the larger of its existing value and the cell’s height.
hx = [0] * n
for y in range(n):
for x in range(n):
hx[x] = max(hx[x], grid[y][x])
Determining the tallest building per row
A second pass computes the maximum height for each row, storing the results in the array hy. The loops are arranged with the outer loop iterating over columns and the inner loop over rows, but the effect is the same: each entry hy[y] ends up holding the greatest height found in row y.
hy = [0] * n
for x in range(n):
for y in range(n):
hy[y] = max(hy[y], grid[y][x])
Accumulating the allowed increase
With the column and row skylines known, the algorithm evaluates every cell again. For a cell at (y, x), the highest height it may attain without changing either skyline is the smaller of the column maximum hx[x] and the row maximum hy[y]. The difference between this limit and the current height is the amount that can be added. Summing these differences across the entire grid yields the final answer.
result = 0
for y in range(n):
for x in range(n):
limit = min(hx[x], hy[y])
result += limit - grid[y][x]
return result
Edge Cases Handled
The algorithm gracefully handles grids where all cells already match the skyline constraints. In such a scenario, each limit equals the original cell value, resulting in a zero contribution to result. The code also works correctly for a grid containing a single row or column because the loops naturally iterate over the single dimension, and the maximum arrays hx and hy each contain a single element. When the grid is composed entirely of zeros, the maximum arrays remain zero, and the final sum stays zero, reflecting that no increase is possible without altering the skyline.
Another subtle edge case involves rows or columns that contain identical maximum values. The max function updates the corresponding entry only when a larger value is encountered, so duplicate maxima do not affect the stored skyline height. Consequently, the min operation in the accumulation phase correctly respects the shared maximum without double-counting.
Performance Optimizations
The implementation avoids auxiliary data structures beyond the two one-dimensional arrays hx and hy. By computing column maxima in a single pass and row maxima in a second pass, it eliminates the need for nested data structures or repeated scans of the same dimension. The use of max and min built-in functions ensures that each comparison is performed in constant time.
The three nested loops each traverse the entire n × n matrix exactly once, resulting in a linear pass over the input size for each phase. This design minimizes cache misses because the inner loops access contiguous memory locations in the row-major order typical of Python lists. Moreover, the final accumulation loop reuses the pre-computed skyline arrays, preventing redundant recomputation of maxima during the summation step.
Overall, the code achieves an efficient balance between clarity and speed, leveraging simple array indexing and built-in operations to keep the runtime overhead low while maintaining a straightforward logical flow.
ELI5 - Simplified Explanation
Imagine a city made of blocks where every building has a different height. A huge bright light is shining from the sides of the city, casting shadows against a screen to see the skyline. The goal is to make the buildings as tall as possible without changing how the skyline looks from the left, right, top, or bottom.
First, the code looks at every row and every column to find the tallest building in each one. It keeps track of these highest heights so the skyline shape stays exactly the same. Think of this like marking the tallest point on the horizon for every direction.
Next, the code goes through every single building one by one. It looks at the tallest building in that specific row and the tallest building in that specific column. It picks the smaller of those two heights because that is the most a building can grow before it starts to poke out and change the shape of the skyline.
Finally, the code calculates how much taller each building can become. It subtracts the building's current height from that special limit and adds that difference to a total pile. This tells everyone how many extra stories can be added to all the buildings together to make the city look grander while keeping the same shadow outline from every side.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| fengvyi | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| fengvyi | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 812: Largest Triangle Area
- problem 824: Goat Latin
- problem 844: Backspace String Compare
- problem 791: Custom Sort String
- problem 794: Valid Tic-Tac-Toe State
- problem 813: Largest Sum of Averages
- problem 814: Binary Tree Pruning
- problem 825: Friends Of Appropriate Ages
- problem 848: Shifting Letters
- problem 849: Maximize Distance to Closest Person
- problem 815: Bus Routes
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality