简体   繁体   English

如何识别重叠日期范围的最大数量?

[英]How to identify the maximum number of overlapping date ranges?

This question might be similar to: 这个问题可能类似于:

But, how can I get the maximum number of overlapping date ranges? 但是,如何获得重叠日期范围的最大数量? (preferably in C#) (最好是在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 结果= 3个最大重叠日期范围

Solution : Possible implementation of the solution proposed by @AakashM 解决方案 :可能实现@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. 其中maxConcurrentCalls将是最大并发日期范围数。

  • For each range, create two Tuple<DateTime, int> s with values start, +1 and end, -1 对于每个范围,创建两个Tuple<DateTime, int> s,其值为start, +1end, -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. 由于排序,在O(n log n)中执行。 There's probably a more efficient way. 可能有一种更有效的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM