Maximum Length Chain of Pairs

There is a chain of pairs is given. In each pair, there are two integers and the first integer is always smaller, and the second one is greater, the same rule can also be applied for the chain construction. A pair (x, y) can be added after a pair (p, q), only if q

To solve this problem, at first, we have to sort given pairs in increasing order of the first element. After that, we will compare the second element of a pair, with the first element of the next pair.

Input and Output

Input:
A chain of number pairs. {(5, 24), (15, 25), (27, 40), (50, 60)}
Output:
Largest length of the chain as given criteria. Here the length is 3.

Algorithm

maxChainLength(arr, n)

Each element of the chain will contain two elements a and b

Input −  The array of pairs, number of items in the array.

Output − Maximum length.

Begin
   define maxChainLen array of size n, and fill with 1
   max := 0

   for i := 1 to n, do
      for j := 0 to i-1, do
         if arr[i].a > arr[j].b and maxChainLen[i] 

Example

#include
#include
using namespace std;

struct numPair {    //define pair as structure
   int a;
   int b;
};

int maxChainLength(numPair arr[], int n) {
   int max = 0;
   int *maxChainLen = new int[n];    //create array of size n

   for (int i = 0; i  arr[j].b && maxChainLen[i] 

Output

Length of maximum size chain is 3
Updated on: 2020-06-17T07:17:54+05:30

675 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements