You are given N ranges of date offsets when N employees are present in an organization. Something like
1-4 (i.e. employee will come on 1st, 2nd, 3rd and 4th day )
2-6
8-9
..
1-14
You have to organize an event on minimum number of days such that each employee can attend the event at least twice.
Q:
你有N个员工的作息时间表(如下),现在你需要安排几个会议,使得每个员工都能够参加会议至少两次,并使得需要安排的会议次数最少。
1-4 (表示该员工会在该月的1,2,3,4号来上班)
A: (很简单的英文,大家将就看看吧)
There isn't O(n) algorithm in total. But if we exclude the sorting part, there is an O(n) algorithm indeed.
Greedy algorithm.
1. sort the ranges in ascending order according to their left bound.
2. delete all ranges which satisfy that there exists at least one bound which is contained by it.
For example, range [a, b]. If there is a range [c, d], (a<=c, d<=b), then we delete [a,b], because if the solution can satisfy [c, d], it can also satisfy [a, b]
3. examine each remaining range from left right. let's say we are examining range Ri=[Ai, Bi], if we already organized at least 2 events between Ai and Bi, then we just pass this range, else we organize new event(s) as near to Bi as possible, to make 2 events in Ai and Bi.
For example, [1, 8], [5, 10], [10, 14], [14, 16]
we check [1, 8] first, and select day-7 and day-8 as the event day. then we check [5, 10], there are already 2 events, pass it. Then [10, 14], we choose day-13 and day-14, then [14, 16], there is only 1 events, we then add day-16 to it. Finished.
It's easy to prove this greedy algorithm is correct as long as no range-containing relationship.
Btw, in step 2, we can use "double-ended queue" to eliminate all [a, b] ranges in O(n)'s time. And we have another way to resolve step 2 issue as following:
Start from the last range after sorting. And maintain a variable range_end_min, which contains the minimum of end values of range seen so far. If for any range end value is more than range_end_min, delete it.
Example..(1,4),(2,9),(5,12),(7,8)
Start from (7,8),range_end_min=8
12>range_end_min, so delete (5,12)
similarly delete (2,9)