You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/1800-1899/1840.Maximum Building Height/README_EN.md
+58-3
Original file line number
Diff line number
Diff line change
@@ -80,7 +80,19 @@ We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest b
80
80
81
81
<!-- solution:start -->
82
82
83
-
### Solution 1
83
+
### Solution 1: Sorting + Mathematics
84
+
85
+
First, we sort all the constraints by the building number in ascending order.
86
+
87
+
Then we traverse all the constraints from left to right. For each constraint, we can get an upper bound on the maximum height, i.e., $r_i[1] = \min(r_i[1], r_{i-1}[1] + r_i[0] - r_{i-1}[0])$, where $r_i$ represents the $i$-th constraint, and $r_i[0]$ and $r_i[1]$ represent the building number and the upper bound on the maximum height of the building, respectively.
88
+
89
+
Next, we traverse all the constraints from right to left. For each constraint, we can get an upper bound on the maximum height, i.e., $r_i[1] = \min(r_i[1], r_{i+1}[1] + r_{i+1}[0] - r_i[0])$.
90
+
91
+
In this way, we obtain the upper bound on the maximum height for each constrained building.
92
+
93
+
The problem asks for the height of the tallest building. We can enumerate the buildings between two adjacent constraints $i$ and $i+1$. To maximize the height, the height should first increase and then decrease. Suppose the maximum height is $t$, then $t - r_i[1] + t - r_{i+1}[1] \leq r_{i+1}[0] - r_i[0]$, i.e., $t \leq \frac{r_i[1] + r_{i+1}[1] + r_{i+1}[0] - r_{i}[0]}{2}$. We take the maximum value of all such $t$.
94
+
95
+
The time complexity is $O(m \times \log m)$, and the space complexity is $O(m)$. Here, $m$ is the number of constraints.
84
96
85
97
<!-- tabs:start -->
86
98
@@ -146,8 +158,10 @@ public:
146
158
int maxBuilding(int n, vector<vector<int>>& restrictions) {
147
159
auto&& r = restrictions;
148
160
r.push_back({1, 0});
149
-
sort(r.begin(), r.end());
150
-
if (r[r.size() - 1][0] != n) r.push_back({n, n - 1});
0 commit comments