Maximum Building Height LeetCode solution in Python

1
# Readability version
2
class Solution:
3
def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:
4
# Set the initial height for the 1st building
5
restrictions.append([1, 0])
6
restrictions.sort()
7

8
# Process restrictions to find the valid ones for reaching previous restrictions
9
valid_restrictions_forward = []
10
temp_diff = 0
11
for id, ht in restrictions:
12
current_diff = id - ht
13
if current_diff >= temp_diff:
14
temp_diff = current_diff
15
valid_restrictions_forward.append([id, ht])
16

17
# Process valid restrictions backward to find the ones for reaching next restrictions
18
valid_restrictions_backward = []
19
temp_sum = n + n - 1
20
for id, ht in valid_restrictions_forward[::-1]:
21
current_sum = id + ht
22
if current_sum <= temp_sum:
23
temp_sum = current_sum
24
valid_restrictions_backward.append([id, ht])
25

26
# Reverse the backward valid restrictions to get the correct order
27
valid_restrictions_backward.reverse()
28

29
# Add maximum height for the last building due to the last restriction
30
if valid_restrictions_backward[-1][0] != n:
31
valid_restrictions_backward.append(
32
[
33
n,
34
valid_restrictions_backward[-1][1]
35
+ n
36
- valid_restrictions_backward[-1][0],
37
]
38
)
39

40
# Calculate the maximum height
41
max_height = 0
42
for i in range(len(valid_restrictions_backward) - 1):
43
x1, y1 = valid_restrictions_backward[i]
44
x2, y2 = valid_restrictions_backward[i + 1]
45
available_height = (-x1 + y1 + x2 + y2) // 2
46
if available_height > max_height:
47
max_height = available_height
48

49
return max_height

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0