educative.io

Can we use same pattern which used in merge interval

Hi
Can we use same pattern which we used for merge interval.
1)we will sort the interval with start time.
2)merge all the interval which overlap and add the cpuload of all the overlap interval ,add these interval in separate list.
3)will get all the distinct interval now and we can traverse all the interval and track the which interval has more cpuload time.

correct me if I am wrong with this approach.

 Collections.sort(intervals, (a, b) -> Integer.compare(a.start, b.start));

 List<Job> mergedIntervals = new LinkedList<Job>();
 Iterator<Job> intervalItr = intervals.iterator();
Interval interval = intervalItr.next();
int start = interval.start;
int end = interval.end;
int load=interval.cpuLoad;
while (intervalItr.hasNext()) {
interval = intervalItr.next();
  if (interval.start <= end) { // overlapping intervals, adjust the 'end'
     end = Math.max(interval.end, end);
      load+=job.cpuLoad;
  } else { // non-overlapping interval, add the previous interval and reset
      mergedIntervals.add(new Job(start, end,load));
       start = interval.start;
      end = interval.end;
        load=interval.cpuLoad;
  }
 }
mergedIntervals.add(new Job(start, end,load));
int max=0;
 for(Job j:mergedIntervals)max=Math.max(max,job.cpuLoad);
return max;
1 Like