Jump to content

Overlapping date range peak


Berre

Recommended Posts

I need some help with creating this algorithm. The goal is to find the highest occurrence of overlapping date ranges.

 

Let's say I have some date ranges:

2012-02-21 - 2012-02-24

2012-02-21 - 2012-02-26

2012-02-23 - 2012-02-29

2012-02-24 - 2012-02-27

2012-02-26 - 2012-02-28

 

Of these the date 2012-02-24 and 2012-02-26 are overlapping 4 times, which is the highest number of overlapping dates. This number (4) is what I want to get. I don't care when the peak is, or how often it peaks, just the highest number of overlapping dates.

 

It's not important with a lot of exact PHP (you don't have to write the entire thing), but I'm completely lost for a simple and fast way of solving this.

post-130872-13482403267248_thumb.png

Link to comment
Share on other sites

In order to find the maximum sum, you would need to iterate over each range of dates and maintain a sum for each date, then simply find the maximum.

 

<?php
$data[] = array('2012-02-21','2012-02-24');
$data[] = array('2012-02-21','2012-02-26');
$data[] = array('2012-02-23','2012-02-29');
$data[] = array('2012-02-24','2012-02-27');
$data[] = array('2012-02-26','2012-02-28');

$arr = array();
foreach($data as $range){
while($range[0] <= $range[1]){
	$arr[$range[0]] = isset($arr[$range[0]]) ? $arr[$range[0]] + 1 :1;
	$range[0] = date('Y-m-d',strtotime($range[0] . '+ 1 day'));
}
}

arsort($arr);
$peak = current($arr);
echo "Peak: $peak";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.