Approach
Sorting and greedy selection
For Maximum Building Height, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 33 lines of C++ from the credited upstream file 1840.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int maxBuilding(int n, vector<vector<int>>& restrictions) {4 vector<vector<int>> A(restrictions);5 6 A.push_back({1, 0});7 A.push_back({n, n - 1});8 ranges::sort(A);9 10 for (int i = 1; i < A.size(); ++i) {11 const int dist = A[i][0] - A[i - 1][0];12 A[i][1] = min(A[i][1], A[i - 1][1] + dist);13 }14 15 for (int i = A.size() - 2; i >= 0; --i) {16 const int dist = A[i + 1][0] - A[i][0];17 A[i][1] = min(A[i][1], A[i + 1][1] + dist);18 }19 20 int ans = 0;21 22 for (int i = 1; i < A.size(); ++i) {23 const int l = A[i - 1][0];24 const int r = A[i][0];25 const int hL = A[i - 1][1];26 const int hR = A[i][1];27 ans = max(ans, max(hL, hR) + (r - l - abs(hL - hR)) / 2);28 }29 30 return ans;31 }32};33