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
- 34 lines of Java from the credited upstream file 1840.java.
- 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 int maxBuilding(int n, int[][] restrictions) {3 final int k = restrictions.length;4 int[][] A = new int[k + 2][2];5 System.arraycopy(restrictions, 0, A, 0, k);6 A[k] = new int[] {1, 0};7 A[k + 1] = new int[] {n, n - 1};8 9 Arrays.sort(A, Comparator.comparingInt((int[] a) -> a[0]).thenComparingInt(a -> a[1]));10 11 for (int i = 1; i < A.length; ++i) {12 final int dist = A[i][0] - A[i - 1][0];13 A[i][1] = Math.min(A[i][1], A[i - 1][1] + dist);14 }15 16 for (int i = A.length - 2; i >= 0; --i) {17 final int dist = A[i + 1][0] - A[i][0];18 A[i][1] = Math.min(A[i][1], A[i + 1][1] + dist);19 }20 21 int ans = 0;22 23 for (int i = 1; i < A.length; ++i) {24 final int l = A[i - 1][0];25 final int r = A[i][0];26 final int hL = A[i - 1][1];27 final int hR = A[i][1];28 ans = Math.max(ans, Math.max(hL, hR) + (r - l - Math.abs(hL - hR)) / 2);29 }30 31 return ans;32 }33}34