Maximum Building Height — LeetCode 1840 Python Solution

HardArrayMathSorting
Problem
#1840
Pattern
Sorting
Reading time
3 min

The problem

You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.

Example

Input
n = 5, restrictions = [[2,1],[4,1]]
Output
2
Explanation
The green area in the image indicates the maximum allowed height for each building.

Python solution

Python
class Solution:
    def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:
        r = restrictions
        r.append([1, 0])
        r.sort()
        if r[-1][0] != n:
            r.append([n, n - 1])
        m = len(r)
        for i in range(1, m):
            r[i][1] = min(r[i][1], r[i - 1][1] + r[i][0] - r[i - 1][0])
        for i in range(m - 2, 0, -1):
            r[i][1] = min(r[i][1], r[i + 1][1] + r[i + 1][0] - r[i][0])
        ans = 0
        for i in range(m - 1):
            t = (r[i][1] + r[i + 1][1] + r[i + 1][0] - r[i][0]) // 2
            ans = max(ans, t)
        return ans

Complexity

MeasureComplexity
TimeO(m \times \log m)
SpaceO(m) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1840. Maximum Building Height is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1840. Maximum Building Height?
LeetCode 1840. Maximum Building Height is rated Hard on LeetCode.
What is the time complexity of LeetCode 1840. Maximum Building Height?
The Python solution on this page runs in O(m \times \log m).
What is the space complexity of LeetCode 1840. Maximum Building Height?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 1840. Maximum Building Height cover?
LeetCode 1840. Maximum Building Height is tagged Array, Math and Sorting 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