Approach
Sorting and greedy selection
For Minimize Connected Groups by Inserting Interval, 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 3323.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 minConnectedGroups(int[][] intervals, int k) {3 int mergedIntervals = 0;4 int maxMergedIntervals = 0;5 6 intervals = merge(intervals);7 8 int i = 0;9 for (int[] interval : intervals) {10 final int end = interval[1];11 while (i < intervals.length && end + k >= intervals[i][0]) {12 ++mergedIntervals;13 ++i;14 }15 --mergedIntervals; 16 maxMergedIntervals = Math.max(maxMergedIntervals, mergedIntervals);17 }18 19 return intervals.length - maxMergedIntervals;20 }21 22 23 public int[][] merge(int[][] intervals) {24 List<int[]> res = new ArrayList<>();25 Arrays.sort(intervals, Comparator.comparingInt((int[] interval) -> interval[0]));26 for (int[] interval : intervals)27 if (res.isEmpty() || res.get(res.size() - 1)[1] < interval[0])28 res.add(interval);29 else30 res.get(res.size() - 1)[1] = Math.max(res.get(res.size() - 1)[1], interval[1]);31 return res.toArray(int[][] ::new);32 }33}34