1
- # Runtime: 4560 ms (Top 6.25%) | Memory: 52.1 MB (Top 56.25%)
1
+ // Runtime : 1203 ms (Top 88.37 % ) | Memory : 55.60 MB (Top 9.3 % )
2
+
3
+ #Readability version
2
4
class Solution :
3
5
def maxBuilding (self , n : int , restrictions : List [List [int ]]) -> int :
4
- arr = restrictions
5
- arr .extend ([[1 ,0 ],[n ,n - 1 ]])
6
- arr .sort ()
7
- n = len (arr )
8
- for i in range (1 ,n ):
9
- arr [i ][1 ] = min (arr [i ][1 ], arr [i - 1 ][1 ]+ arr [i ][0 ]- arr [i - 1 ][0 ])
10
- for i in range (n - 2 ,- 1 ,- 1 ):
11
- arr [i ][1 ] = min (arr [i ][1 ], arr [i + 1 ][1 ]+ arr [i + 1 ][0 ]- arr [i ][0 ])
12
- res = 0
13
- for i in range (1 ,n ):
14
- #position where height can be the highest between arr[i-1][0] and arr[i][0]
15
- k = (arr [i ][1 ]- arr [i - 1 ][1 ]+ arr [i ][0 ]+ arr [i - 1 ][0 ])// 2
16
- res = max (res , arr [i - 1 ][1 ]+ k - arr [i - 1 ][0 ])
17
- return res
6
+ # Set the initial height for the 1st building
7
+ restrictions .append ([1 , 0 ])
8
+ restrictions .sort ()
9
+
10
+ # Process restrictions to find the valid ones for reaching previous restrictions
11
+ valid_restrictions_forward = []
12
+ temp_diff = 0
13
+ for id , ht in restrictions :
14
+ current_diff = id - ht
15
+ if current_diff >= temp_diff :
16
+ temp_diff = current_diff
17
+ valid_restrictions_forward .append ([id , ht ])
18
+
19
+ # Process valid restrictions backward to find the ones for reaching next restrictions
20
+ valid_restrictions_backward = []
21
+ temp_sum = n + n - 1
22
+ for id , ht in valid_restrictions_forward [::- 1 ]:
23
+ current_sum = id + ht
24
+ if current_sum <= temp_sum :
25
+ temp_sum = current_sum
26
+ valid_restrictions_backward .append ([id , ht ])
27
+
28
+ # Reverse the backward valid restrictions to get the correct order
29
+ valid_restrictions_backward .reverse ()
30
+
31
+ # Add maximum height for the last building due to the last restriction
32
+ if valid_restrictions_backward [- 1 ][0 ] != n :
33
+ valid_restrictions_backward .append ([n , valid_restrictions_backward [- 1 ][1 ] + n - valid_restrictions_backward [- 1 ][0 ]])
34
+
35
+ # Calculate the maximum height
36
+ max_height = 0
37
+ for i in range (len (valid_restrictions_backward ) - 1 ):
38
+ x1 , y1 = valid_restrictions_backward [i ]
39
+ x2 , y2 = valid_restrictions_backward [i + 1 ]
40
+ available_height = (- x1 + y1 + x2 + y2 ) // 2
41
+ if available_height > max_height :
42
+ max_height = available_height
43
+
44
+ return max_height
45
+
0 commit comments