Print Maximum Length Chain of Pairs
An N pair array is given to you. In every pair, the first number is always smaller than the second number. A pair (a,b) can follow another pair (c,d) if a is greater than d. Two pairs are joined with this logic. Your task is to join this set of pairs and print the pairs of the chain.
Input:
T-test cases.
N no. of pairs are given.
E.g.
3
8
4 5 6 9 1 2 15 26 7 8 10 17 5 9 8 17
6
5 8 11 15 6 10 12 17 11 14 15 16
2
2 10 6 12
Output:
Print pairs of the chain.
Example
T = 3
Input:
8
4 5 6 9 1 2 15 26 7 8 10 17 5 9 8 17
Output:
1 2 4 5 7 8 15 26
Input:
6
5 8 11 15 6 10 12 17 11 14 15 16
Output:
6 10 11 14 15 16
Input:
2
2 10 6 12
Output:
6 12
To print the longest chain from N pairs is a problem of combination and permutation. If we go with the recursive approach then it will take a long time.
let f(i) = maximum chain length among ith pairs.
To solve this problem, we will follow these steps,
f(current element)=max(f(current element), f(element having the second element is smaller than it)).
To print the chains, we follow this approach,
C++ Implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer