How to identify the maximum number of overlapping date ranges?

谁说胖子不能爱 提交于 2019-12-20 04:24:21

问题


This question might be similar to:

  • Determine Whether Two Date Ranges Overlap
  • Multiple Date range comparison for overlap: how to do it efficiently?

But, how can I get the maximum number of overlapping date ranges? (preferably in C#)

Example: (from - to)

01/01/2012 - 10/01/2012
03/01/2012 - 08/01/2012
09/01/2012 - 15/01/2012
11/01/2012 - 20/01/2012
12/01/2012 - 14/01/2012

Result = 3 maximum overlapping date ranges

Solution: Possible implementation of the solution proposed by @AakashM

List<Tuple<DateTime, int>> myTupleList = new List<Tuple<DateTime, int>>();

foreach (DataRow row in objDS.Tables[0].Rows) // objDS is a DataSet with the date ranges
{
    var myTupleFrom = new Tuple<DateTime, int>(DateTime.Parse(row["start_time"].ToString()), 1);
    var myTupleTo = new Tuple<DateTime, int>(DateTime.Parse(row["stop_time"].ToString()), -1);
    myTupleList.Add(myTupleFrom);
    myTupleList.Add(myTupleTo);
}

myTupleList.Sort();

int maxConcurrentCalls = 0;
int concurrentCalls = 0;
foreach (Tuple<DateTime,int> myTuple in myTupleList)
{
    if (myTuple.Item2 == 1)
    {
        concurrentCalls++;
        if (concurrentCalls > maxConcurrentCalls)
        {
            maxConcurrentCalls = concurrentCalls;
        }
    }
    else // == -1
    {
        concurrentCalls--;
    }
}

Where maxConcurrentCalls will be the maximum number of concurrent date ranges.


回答1:


  • For each range, create two Tuple<DateTime, int>s with values start, +1 and end, -1
  • Sort the collection of tuples by date
  • Iterate through the sorted list, adding the number part of the tuple to a running total, and keeping track of the maximum value reached by the running total
  • Return the maximum value the running total reaches

Executes in O(n log n) because of the sort. There's probably a more efficient way.



来源:https://stackoverflow.com/questions/11956589/how-to-identify-the-maximum-number-of-overlapping-date-ranges

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!