Sunday, January 12, 2014

Longest chain of non-overlapping intervals (activity selection)

Problem:
You are given pairs of numbers. In a pair the first number is smaller with respect to the second number. Suppose you have two sets (a, b) and (c, d), the second set can follow the first set if b<c.So you can form a long chain in the similar fashion. Find the longest chain which can be formed

Solution:
This is known as Activity selection problem. Using a greedy algorithm to find a solution will always result in an optimal solution:

Sort the set of activities by finishing time (f[i])
S = {1}
f = f[1]
for i=2 to n
   if s[i] ≥ f
      S = S U i
      f = f[i]
endfor

Basically, we always choose an interval with the minimum possible finish-time, thus allowing us to build the longest chain using the rest of the intervals.

Complexity:
time - O(n log n)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=5068766153015296
http://en.wikipedia.org/wiki/Activity_selection_problem

No comments:

Post a Comment