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

标签 c# date date-range

这个问题可能类似于:

但是,我怎样才能获得重叠日期范围的最大数量? (最好使用 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 将是并发日期范围的最大数量。

最佳答案

  • 为每个范围创建两个 Tuple<DateTime, int> s 的值为 start, +1end, -1
  • 按日期对元组集合进行排序
  • 遍历排序后的列表,将元组的数字部分添加到总计中,并跟踪总计达到的最大值
  • 返回运行总和达到的最大值

O(n log n) 中执行因为排序。可能有更有效的方法。

关于c# - 如何识别重叠日期范围的最大数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11956589/

相关文章:

c# - 如何对事件日志中的 .NET 2.0 错误报告消息进行故障排除?

c# - 有返回值的存储过程

Java 从 LocalDateTime Bar 中减去 LocalDateTime foo

sql - 聚合时间序列中的每一天,不使用非等值连接逻辑

sql - 在 PostgreSQL 中按用户展平相交时间跨度

sql - 如何在 SQL 数据库中存储绝对和相对日期范围?

c# - 按枚举排序 List<T>,其中枚举乱序

PHP 日期字符串格式

mysql - 使用 mysql 按数据导入日期按日期在现有数据集中查找唯一/新值

c# - 在 Elasticsearch 中将英语分析器添加到类型