【问题标题】:How to identify the maximum number of overlapping date ranges?如何确定重叠日期范围的最大数量?
【发布时间】:2012-08-14 16:19:21
【问题描述】:

这个问题可能类似于:

但是,我怎样才能获得重叠日期范围的最大数量? (最好在 C# 中)

示例:(从 - 到)

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

结果 = 3 个最大重叠日期范围

解决方案:@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--;
    }
}

其中maxConcurrentCalls 将是最大并发日期范围数。

【问题讨论】:

  • 你的意思是“总数”的“最大数量”还是给定范围数量的理论上可能的最大数量?
  • 最大数量。还有其他 2 个重叠范围,但我只关心这个特定场景的最大数量
  • 现在我明白你的意思了。您想知道在同一日期子范围内重叠的最大范围数。在 12/01 和 14/01 之间,这三个范围 (09/01-15/01)、(11/01-20/01) 和 (12/01-14/01) 确实重叠。

标签: c# date date-range


【解决方案1】:
  • 为每个范围创建两个Tuple&lt;DateTime, int&gt;s,其值为start, +1end, -1
  • 按日期对元组集合进行排序
  • 遍历排序列表,将元组的数字部分添加到运行总计中,并跟踪运行总计达到的最大值
  • 返回累计达到的最大值

由于排序,在O(n log n) 中执行。可能有更有效的方法。

【讨论】:

  • 感谢您的回答!请检查添加到问题中的实现
猜你喜欢
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
相关资源
最近更新 更多