The standard solution is to process the intervals into a set of (begin,end) points. For example (1,3)
generates {1, begin}
, {3, end}
. Then sort the points and scan left to right, counting begin
as +1, end
as -1. The max value reached by the counter is the maximum number of overlapping intervals.
This is the intermediate array generated from the example in the question:
[(1, 'begin'),
(3, 'begin'),
(5, 'end'),
(6, 'begin'),
(7, 'begin'), # <--- counter reaches 3, its maximum value here.
(8, 'end'),
(9, 'end'), (10, 'end')]
There is a minor tricky point here. Does (1,end)
go before or after (1,begin)
? If you treat intervals as open, then it should go before - this way (0,1)
& (1,2)
won't be counted as intersecting. Otherwise it should go after and these intervals will count as intersecting ones.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…