Given n pairs of numbers the first number is always smaller than the second number. A pair (c, d) can follow a pair (a, b) if and only if b <= c. Chain of pairs can be formed in this fashion. Find the longest chain which can be formed from a given set of pairs.
e.g. { (1,2), (3,4), (5,7), (9,10), (7,9), (8,9), (0,6) }
So the output should be : {(1,2), (3,4), (5,7), (8,9), (9,10)}
My Algorithm for this is as below:
1. Sort the list according to the 2nd number of elements
i.e.`{ (1,2), (3,4), (0,6), (5,7), (7,9), (8,9), (9,10) }`
2. choose the first element from the list i.e. `(1,2)`
3. for each element e in the list left
4. choose this element e if the first number of the element is greater than the 2nd number of the previous element. i.e. after `(1,2)` choose `(3,4)` because `3 > 2.`
After the above algorithm you will have the output as {(1,2), (3,4), (5,7), (8,9), (9,10)}
.
Please let me know about the correctness of the algorithm. Thanks.
EDIT:
A more intuitive proof of correctness:
Proof: The only way to include more pairs in the chain is to replace a pair with one with a smaller Y value, to allow for the next pair to have a smaller X value, potentially fitting another pair where it couldn't fit before. If you replace a pair with one with the same Y value, you gain nothing. If the replacement has a larger Y value, all you've done is potentially block some pairs that would've fit before.
Because the pairs have been sorted by Y values, you will never find a replacement with a smaller Y. Looking "forward" in the sorted pairs, they will all have the same or greater Y value. Looking "backward", any that were eliminated from the chain initially were because the X value wasn't high enough, which will still be the case.
This is taken from here