Approach
Sorting and greedy selection
For Amount of New Area Painted Each Day, 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
- 39 lines of Java from the credited upstream file 2158.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 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.
1enum Type { ENTERING, LEAVING }2 3class Solution {4 public int[] amountPainted(int[][] paint) {5 record Event(int day, int index, Type type) {}6 final int n = paint.length;7 final int minDay = Arrays.stream(paint).mapToInt(x -> x[0]).min().getAsInt();8 final int maxDay = Arrays.stream(paint).mapToInt(x -> x[1]).max().getAsInt();9 int[] ans = new int[n];10 11 TreeSet<Integer> runningIndices = new TreeSet<>();12 List<Event> events = new ArrayList<>();13 14 for (int i = 0; i < n; ++i) {15 final int start = paint[i][0];16 final int end = paint[i][1];17 events.add(new Event(start, i, Type.ENTERING)); 18 events.add(new Event(end, i, Type.LEAVING)); 19 }20 21 Collections.sort(events, Comparator.comparingInt(Event::day));22 23 int i = 0; 24 for (int day = minDay; day < maxDay; ++day) {25 while (i < events.size() && events.get(i).day == day) {26 if (events.get(i).type == Type.ENTERING)27 runningIndices.add(events.get(i).index);28 else29 runningIndices.remove(events.get(i).index);30 ++i;31 }32 if (!runningIndices.isEmpty())33 ++ans[runningIndices.first()];34 }35 36 return ans;37 }38}39