Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum building height in Python
Suppose we have a value n and another list of pairs called restrictions. We want to build n new buildings in a city with specific constraints. Buildings are placed in a line and labeled from 1 to n. Each restriction has the format restrictions[i] = (id_i, max_height_i), indicating that building id_i must have height less than or equal to max_height_i.
The city has the following height restrictions −
The height of each building must be 0 or positive values.
First building height must be 0.
The difference between any two adjacent buildings height cannot exceed 1.
We need to find the maximum possible height of the tallest building.
Algorithm
The solution uses a three-pass approach to handle constraints ?
Forward pass: Ensure heights don't violate restrictions considering left-to-right adjacency
Backward pass: Ensure heights don't violate restrictions considering right-to-left adjacency
Final pass: Calculate the maximum possible height considering all constraints
Implementation
def solve(n, restrictions):
if not restrictions:
return n-1
# Sort restrictions by building id
resi = sorted(restrictions, key=lambda x: x[0])
# Forward pass: adjust heights based on left neighbors
k = 0
idx = 1
for re in resi:
re[1] = min(re[1], k + re[0] - idx)
k = re[1]
idx = re[0]
# Backward pass: adjust heights based on right neighbors
k = resi[-1][1]
idx = resi[-1][0]
resi.reverse()
for re in resi[1:]:
re[1] = min(re[1], k - re[0] + idx)
k = re[1]
idx = re[0]
resi.reverse()
# Calculate maximum possible height
f = 0
idx = 1
res = 0
for re in resi:
ff = min(f + re[0] - idx, re[1])
res = max(res, (re[0] - idx + f + ff) // 2)
idx = re[0]
f = ff
return max(f + n - idx, res)
# Test the function
n = 5
restrictions = [[2, 1], [4, 3]]
result = solve(n, restrictions)
print(f"Maximum building height: {result}")
Maximum building height: 4
Example Walkthrough
For n = 5 and restrictions = [[2,1],[4,3]] ?
Building 2 height ? 1
Building 4 height ? 3
Adjacent height difference ? 1
Building 1 height = 0
The optimal configuration is: [0, 1, 2, 3, 4] with maximum height 4.
Time and Space Complexity
Time Complexity: O(r log r) where r is the number of restrictions (due to sorting)
Space Complexity: O(1) excluding input storage
Conclusion
This algorithm efficiently finds the maximum building height by using a three-pass approach to handle adjacency constraints. The key insight is processing restrictions in both forward and backward directions to ensure optimal height distribution.
