## Monday, August 8, 2016

### Maximum number of overlapping intervals - Merge Overlapping Intervals - Max Task Load - Algorithms and Problem SolvingAlgorithms and Problem Solving

Maximum number of overlapping intervals - Merge Overlapping Intervals - Max Task Load - Algorithms and Problem SolvingAlgorithms and Problem Solving
Given a set of intervals, how do we find the maximum number of intervals overlapping at any point of time.
if an interval starts and if we increment a counter during a start and decrement the counter during an end then if there is no interval overlapped to this count is always zero. This signals us a way to solve this problem i.e. sort the start and end points as separate arrays and count the overlaps by doing a merge operation on the two sorted arrays.
let’s consider all the start and end point as separate arrays.
• Sort starting points and ending points in ascending order separately. For example, s=[0, 1, 3, 4, 7] and end=[2, 5, 6, 7, 8].
• Do merge of start and end by maintaining two pointers i and j respectively in the two arrays.
• Keep track of the current overlap and maximum overlap we have seen so far during merge.
• Two cases
• If start[i] < end[i] : we know that a new range begins. So increment the current counter and update value of max counter. For example, we take first 2 starts , s=0,1 until we see an end, e = 2. so count=2.
• Otherwise : It’s an end point of a range so we decrement the counter. For example, when we see end point, e= 2 we update count = 2-1 = 1. And so on.
• At the end of this process, we have the answer in max counter.
```public static int maxOverlapIntervalCount(int[] start, int[] end){
int maxOverlap = 0;
int currentOverlap = 0;

Arrays.sort(start);
Arrays.sort(end);

int i = 0;
int j = 0;
int m=start.length,n=end.length;
while(i< m && j < n){
if(start[i] < end[j]){
currentOverlap++;
maxOverlap = Math.max(maxOverlap, currentOverlap);
i++;
}
else{
currentOverlap--;
j++;
}
}

return maxOverlap;
}```

Given a list of n Jobs with start time, end time and CPU load when it is active at any moment. If all the jobs are running at the same machine then find the maximum CPU load at any time.
For example, let’s define a job as a tuple of (start_time, end_time, weight) where weight is the load of that job at any time when active. Then,
```public static int maxLoad(Job[] jobs){
int maxLoad = 0;
int curLoad = 0;

Job[] start = Arrays.copyOf(jobs, jobs.length);
Job[] end = Arrays.copyOf(jobs, jobs.length);

Arrays.sort(start, new Comparator<Job>() {

@Override
public int compare(Job o1, Job o2) {
return Integer.compare(o1.start, o2.start);
}
});
Arrays.sort(end, new Comparator<Job>() {

@Override
public int compare(Job o1, Job o2) {
return Integer.compare(o1.finish , o2.finish);
}
});

int i = 0, j = 0;
while(i < start.length && j < end.length){
if(start[i].start <= end[j].finish){
i++;
}
else{
j++;
}
}

}```

Merge Overlapping Intervals
Now, let’s consider how we can merge overlapping intervals.
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
```def merge(intervals):
result = empty Set;
sort(intervals, StartBasedComparator)
prev = intervals[0];
for i = 1 to n-1
cur = intervals[i];
if cur.start < prev.end then
prev = new Interval(start=prev.start, end = max(cur.end, prev.end));
else
prev = cur;
end
end loop;
return result;
```
Insert a New Interval Into a Sorted Array Of Intervals
We can scan the sorted intervals from left to right and try to merge. There are 3 cases
• Case 1:New interval completely falls right side of current interval with no overlap. In this case current interval is taken and added to result as the new interval may get merged to other interval that starts after current interval.
• Case 2:New interval completely falls left side of current interval with no overlap. In this case new interval is taken and added to result as the it ends before current starts.
• Case 3:New interval overlaps with current interval. So, we will have a new interval that is a merged interval of current interval and new interval.
```def insert(intervals, newInterval) :
result = empty set of intervals.
foreach interval curInterval in intervals
if curInterval.end < newInterval.start then
else if curInterval.start > newInterval.end then
newInterval = curInterval;
else
newInterval = new Interval(min(curInterval.start, newInterval.start),max(curInterval.end, newInterval.end));
end loop;
return result;```
Google – Maximum Time Range Overlaps

search interval是给一个idx，找出有多少个包含它的interval

[Solution]

1. merge interval
2. interval tree
3. scan-line

Merge Interval可以做，不过写merge interval要做到一遍bug free实在太难了。
interval tree的话其实也是Merge, 就inorder traversal来merge，也麻烦，建树还要traversal的
scan-line是最新学会的一种算法，对Interval的题目特别好用，这道题很明显scan-line的实现难易度比前两种都要简单。不过要注意一点，scan-line也是要sort的，不是O(n)就能解决
`  ``public` `int` `maximumOverlap(TimeRange[] times) {`
`    ``List<Line> list = ``new` `ArrayList<>();`
`    ``for` `(TimeRange time : times) {`
`      ``list.add(``new` `Line(time.start, ``true``));`
`      ``list.add(``new` `Line(time.end, ``false``));`
`    ``}`
`    `
`    ``Collections.sort(list, ``new` `Comparator<Line>() {`
`      ``public` `int` `compare(Line a, Line b) {`
`        ``if` `(a.x == b.x) {`
`          ``return` `a.isStart? -``1` `: ``1``;`
`        ``}`
`        `
`        ``return` `a.x - b.x;`
`      ``}`
`    ``});`
`    `
`    ``int` `cnt = ``0``;`
`    ``for` `(``int` `i = ``0``; i < list.size(); i++) {`
`      ``if` `(list.get(i).isStart) {`
`        ``cnt++;`
`        ``list.get(i).cnt = cnt;`
`        ``result = Math.max(result, cnt);`
`      ``}`
`      ``else` `{`
`        ``list.get(i).cnt = cnt;`
`        ``cnt--;`
`      ``}`
`    ``}`
`    `
`    ``return` `result;`
`  ``} `
`  `
`  ``private` `class` `Line {`
`    ``int` `x;`
`    ``boolean` `isStart;`
`    ``int` `cnt;`
`    `
`    ``public` `Line(``int` `x, ``boolean` `isStart) {`
`      ``this``.x = x;`
`      ``this``.isStart = isStart;`
`    ``}`
`  ``} `

Read full article from Maximum number of overlapping intervals - Merge Overlapping Intervals - Max Task Load - Algorithms and Problem SolvingAlgorithms and Problem Solving