Max Increase to Keep City Skyline — LeetCode 807 Python Solution

MediumGreedyArrayMatrix
Problem
#807
Reading time
2 min

The 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.

Example

Input
grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output
35
Explanation
The building heights are shown in the center of the above image.

Python solution

Python
class Solution:
    def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
        row_max = [max(row) for row in grid]
        col_max = [max(col) for col in zip(*grid)]
        return sum(
            min(row_max[i], col_max[j]) - x
            for i, row in enumerate(grid)
            for j, x in enumerate(row)
        )

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n), where n is the side length of the matrix \textit{grid} auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 807. Max Increase to Keep City Skyline is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 807. Max Increase to Keep City Skyline?
LeetCode 807. Max Increase to Keep City Skyline is rated Medium on LeetCode.
What is the time complexity of LeetCode 807. Max Increase to Keep City Skyline?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 807. Max Increase to Keep City Skyline?
The Python solution on this page uses O(n), where n is the side length of the matrix \textit{grid} auxiliary space.
What topics does LeetCode 807. Max Increase to Keep City Skyline cover?
LeetCode 807. Max Increase to Keep City Skyline is tagged Greedy, Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview