#1840

Maximum Building Height

Hard
ArrayMathSortingSortingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution involves processing the restrictions in two passes: one from left to right and another from right to left. This allows us to calculate the maximum possible height for each building while respecting the restrictions.

⚙️

Algorithm

4 steps
  1. 1Step 1: Add the first building with height 0 to the restrictions list and sort the restrictions based on building IDs.
  2. 2Step 2: Traverse the sorted restrictions from left to right, calculating the maximum height for each building based on the previous building's height and the current restriction.
  3. 3Step 3: Traverse the sorted restrictions from right to left, applying the same logic to ensure the heights are valid in both directions.
  4. 4Step 4: Calculate the maximum height possible between each pair of buildings based on the adjusted heights.
solution.py13 lines
1# Full working Python code
2
3def maxBuilding(n, restrictions):
4    restrictions.append([1, 0])
5    restrictions.append([n, n])
6    restrictions.sort()
7    max_height = 0
8    for i in range(1, len(restrictions)):
9        left_id, left_height = restrictions[i - 1]
10        right_id, right_height = restrictions[i]
11        height = (right_height + left_height + (right_id - left_id)) // 2
12        max_height = max(max_height, height)
13    return max_height

Complexity note: The time complexity is dominated by the sorting step, while the space complexity accounts for storing the restrictions.

  • 1Understanding how to manage height restrictions is key to solving this problem.
  • 2Two passes (left to right and right to left) help ensure that all restrictions are respected.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.