import java.util.Comparator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MergeRanges {
public static List<int[]> mergeRanges(List<int[]> ranges) {
// Sort by start value
ranges.sort(Comparator.comparingInt(a -> a[0]));
List<int[]> merged = new ArrayList<>();
for (int[] r : ranges) {
int start = r[0];
int end = r[1];
if (merged.isEmpty() || start > merged.get(merged.size() - 1)[1]) {
merged.add(new int[]{start, end});
} else {
int[] last = merged.get(merged.size() - 1);
last[1] = Math.max(last[1], end);
}
}
return merged;
}
public static void main(String[] args) {
List<int[]> ranges = Arrays.asList(
new int[]{302, 447},
new int[]{488, 489},
new int[]{121, 234},
new int[]{200, 421},
new int[]{140, 354}
);
List<int[]> result = mergeRanges(ranges);
for (int[] r : result) {
System.out.println("(" + r[0] + ", " + r[1] + ")");
}
}
}
/*
run:
(121, 447)
(488, 489)
*/