Skip to content

1840. Maximum Building Height 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
 public:
  int maxBuilding(int n, vector<vector<int>>& restrictions) {
    vector<vector<int>> A(restrictions);

    A.push_back({1, 0});
    A.push_back({n, n - 1});
    sort(begin(A), end(A));

    for (int i = 1; i < A.size(); ++i) {
      const int dist = A[i][0] - A[i - 1][0];
      A[i][1] = min(A[i][1], A[i - 1][1] + dist);
    }

    for (int i = A.size() - 2; i >= 0; --i) {
      const int dist = A[i + 1][0] - A[i][0];
      A[i][1] = min(A[i][1], A[i + 1][1] + dist);
    }

    int ans = 0;

    for (int i = 1; i < A.size(); ++i) {
      const int l = A[i - 1][0];
      const int r = A[i][0];
      const int hL = A[i - 1][1];
      const int hR = A[i][1];
      ans = max(ans, max(hL, hR) + (r - l - abs(hL - hR)) / 2);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
  public int maxBuilding(int n, int[][] restrictions) {
    final int k = restrictions.length;
    int[][] A = new int[k + 2][2];
    System.arraycopy(restrictions, 0, A, 0, k);
    A[k] = new int[] {1, 0};
    A[k + 1] = new int[] {n, n - 1};

    Arrays.sort(A, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);

    for (int i = 1; i < A.length; ++i) {
      final int dist = A[i][0] - A[i - 1][0];
      A[i][1] = Math.min(A[i][1], A[i - 1][1] + dist);
    }

    for (int i = A.length - 2; i >= 0; --i) {
      final int dist = A[i + 1][0] - A[i][0];
      A[i][1] = Math.min(A[i][1], A[i + 1][1] + dist);
    }

    int ans = 0;

    for (int i = 1; i < A.length; ++i) {
      final int l = A[i - 1][0];
      final int r = A[i][0];
      final int hL = A[i - 1][1];
      final int hR = A[i][1];
      ans = Math.max(ans, Math.max(hL, hR) + (r - l - Math.abs(hL - hR)) / 2);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:
    A = sorted(restrictions + [[1, 0]] + [[n, n - 1]])

    for i in range(len(A)):
      dist = A[i][0] - A[i - 1][0]
      A[i][1] = min(A[i][1], A[i - 1][1] + dist)

    for i in reversed(range(len(A) - 1)):
      dist = A[i + 1][0] - A[i][0]
      A[i][1] = min(A[i][1], A[i + 1][1] + dist)

    ans = 0

    for (l, hL), (r, hR) in zip(A, A[1:]):
      ans = max(ans, max(hL, hR) + (r - l - abs(hL - hR)) // 2)

    return ans