Imagine you have a variable $n denoting a number of partitions on a timeline, and a variable length array of intervals:
$n = 10;
$intervals = [
[1, 2],
[2, 2],
[5, 6],
[8, 10],
];
The problem is to find the largest gap between these intervals on the timeline. For the above question, we have two gaps of lengths 2 and 1, so the answer should be 2. To better visualize it:
My straight forward approach is not efficient...
- Initialize an empty timeline array of length $n with each element set to 'E' as in empty.
- Foreach loop over each interval and create another for loop from interval start to interval finish and set those elements in the timeline array to 'T' as in taken.
- Loop over the timeline array and initiate a $counter that increments with each consecutive 'E' characters, then save its value to a variable $max if it is greater than the previous.
What improvements can I do?
Please note:
- Intervals are always sorted in respect to their start positions.
- Intervals don't have to start from the beginning of the timeline nor do they have to end at the timeline's end as well. So, there might be a gap before the first interval and a gap after the last interval.
- Intervals can overlap. So simply calculating the next interval's start minus this interval's finish will not work... Consider this example: [1,5] [2,4] [6,10] [6,8]


