Approach
Sorting and greedy selection
For Separate Squares I, 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 3453.java.
- The implementation visibly relies on sequence storage.
- 2 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 double separateSquares(int[][] squares) {3 final double halfArea =4 Arrays.stream(squares).mapToDouble(square -> Math.pow(square[2], 2)).sum() / 2;5 List<int[]> events = new ArrayList<>();6 7 for (int[] square : squares) {8 final int y = square[1];9 final int l = square[2];10 events.add(new int[] {y, 1, l}); 11 events.add(new int[] {y + l, 0, l}); 12 }13 14 events.sort(Comparator.comparingInt(event -> event[0]));15 16 double area = 0;17 int width = 0;18 int prevY = 0;19 20 for (int[] event : events) {21 final int y = event[0];22 final int l = event[2];23 final double areaGain = width * (long) (y - prevY);24 if (area + areaGain >= halfArea)25 return prevY + (halfArea - area) / width;26 area += areaGain;27 width += (event[1] == 1) ? l : -l;28 prevY = y;29 }30 31 throw new IllegalArgumentException();32 }33}34