Finding (number of) overlaps in a list of time ranges

后端 未结 9 652
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 19:53

Given a list of time ranges, I need to find the maximum number of overlaps.

Following is a dataset showing a 10 minute interval of calls, from which I am trying to f

9条回答
  •  醉话见心
    2020-12-04 20:14

    It's amazing how for some problems solutions sometimes just pop out of one mind... and I think I probably the simplest solution ;)

    You can represent the times in seconds, from the beginning of your range (0) to its end (600). A call is a pair of times.

    Python algorithm:

    def maxSimultaneousCalls(calls):
      """Returns the maximum number of simultaneous calls
      calls   : list of calls
        (represented as pairs [begin,end] with begin and end in seconds)
      """
      # Shift the calls so that 0 correspond to the beginning of the first call
      min = min([call[0] for call in calls])
    
      tmpCalls = [(call[0] - min, call[1] - min) for call in calls]
      max = max([call[1] for call in tmpCalls])
    
      # Find how many calls were active at each second during the interval [0,max]
      seconds = [0 for i in range(0,max+1)]
      for call in tmpCalls:
        for i in range(call[0],call[1]):
          seconds[i] += 1
    
      return max(seconds)
    

    Note that I don't know which calls were active at this time ;)

    But in term of complexity it's extremely trivial to evaluate: it's linear in term of the total duration of the calls.

提交回复
热议问题