The question does not indicate whether the start and end times will be set in pairs or separately. There is a simple algorithm for the less simple case when they are listed separately. Thus, we have all the time in one list, but we save information if it starts working hours or ends working hours.
eg:
13:00 start 15:00 finish 8:30 start 10:00 finish 9:00 start 12:00 finish
then sort this list by time:
8:30 start 9:00 start 10:00 finish 12:00 finish 13:00 start 15:00 finish
We need a counter for open jobs, and we can process the list, increase the counter when the start time of the processing and the decrease counter when processing the end time; If the counter is 0, it means that we are entering a state of inaction.
list.sort() open_jobs = 0 state_changed_time = list[0].time; max_idle_interval = -1; max_not_idle_interval = -1; for each (element in list) { if (element.type == start) { if(open_jobs == 0) { interval = element.time - state_changed_time; if (interval > max_idle_interval) max_idle_interval = interval; state_changed_time = element.time; } open_jobs +=1; } if (element.type == finish) { open_jobs -= 1; if(open_jobs == 0) { interval = element.time - state_changed_time; if (interval > max_not_idle_interval) max_not_idle_interval = interval; state_changed_time = element.time; } } }
source share