Approach
Sorting and greedy selection
For Two Best Non-Overlapping Events, 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
- 27 lines of Java from the credited upstream file 2054.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 int maxTwoEvents(int[][] events) {3 record Event(int time, int value, int isStart) {}4 int ans = 0;5 int maxValue = 0;6 Event[] evts = new Event[events.length * 2];7 8 for (int i = 0; i < events.length; ++i) {9 final int start = events[i][0];10 final int end = events[i][1];11 final int value = events[i][2];12 evts[i * 2] = new Event(start, value, 1);13 evts[i * 2 + 1] = new Event(end + 1, value, 0);14 }15 16 Arrays.sort(evts, Comparator.comparingInt(Event::time).thenComparingInt(Event::isStart));17 18 for (Event evt : evts)19 if (evt.isStart == 1)20 ans = Math.max(ans, evt.value + maxValue);21 else22 maxValue = Math.max(maxValue, evt.value);23 24 return ans;25 }26}27