Maximum Length Chain of Pairs in C++

C++Server Side ProgrammingProgramming

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.


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.
   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
   max := maximum length in maxChainLen array
   return max


Live Demo

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);


Length of maximum size chain is 3
Published on 25-Sep-2019 15:57:19