# Maximum Length Chain of Pairs in C++

There is a chain of pairs is given. In each pair, there are two integers and the first integer is always smaller, and 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 < x.

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

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 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] < maxChainLen[j] + 1
maxChainLen[i] := maxChainLen[j] + 1
done
done
max := maximum length in maxChainLen array
return max
End

## Example

Live Demo

#include<iostream>
#include<algorithm>
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 < n; i++ ) //Initialize Max Chain length values for all indexes
maxChainLen[i] = 1;
for (int i = 1; i < n; i++ )
for (int j = 0; j < i; j++ )
if ( arr[i].a > arr[j].b && maxChainLen[i] < maxChainLen[j] + 1)
maxChainLen[i] = maxChainLen[j] + 1;
// maxChainLen[i] now holds the max chain length ending with pair i
for (int i = 0; i < n; i++ )
if ( max < maxChainLen[i] )
max = maxChainLen[i]; //find maximum among all chain length values
delete[] maxChainLen; //deallocate memory
return max;
}
int main(){
struct numPair arr[] = {{5, 24},{15, 25},{27, 40},{50, 60}};
int n = 4;
cout << "Length of maximum size chain is " << maxChainLength(arr, n);
}

## Output

Length of maximum size chain is 3

Updated on: 25-Sep-2019

75 Views 