Maximum Length Chain of Pairs | Set-2

• Difficulty Level : Medium
• Last Updated : 17 Dec, 2021

Given an array of pairs of numbers of size N. In every pair, the first number is always smaller than the second number. A pair (c, d) can follow another pair (a, b) if b < c. The chain of pairs can be formed in this fashion. The task is to find the length of the longest chain which can be formed from a given set of pairs.

Examples:

Input: N = 5, arr={{5, 24}, {39, 60}, {15, 28}, {27, 40}, {50, 90} }
Output:
The longest chain that can be formed is of length 3, and the chain is {{5, 24}, {27, 40}, {50, 90}}.

Input : N = 2, arr={{5, 10}, {1, 11}}
Output :

Approach: A dynamic programming approach for the problem has been discussed here
Idea is to solve the problem using the greedy approach which is the same as Activity Selection Problem

• Sort all pairs in increasing order of second number of each pair.
• Select first no as the first pair of chain and set a variable s(say) with the second value of the first pair.
• Iterate from the second pair to last pair of the array and if the value of the first element of the current pair is greater then previously selected pair then select the current pair and update the value of maximum length and variable s.
• Return the value of Max length of chain.

Below is the implementation of the above approach.

C++

 `// C++ implementation of the above approach``#include ``using` `namespace` `std;` `// Comparator function which can compare``// the second element of the pair used to``// sort pairs in increasing order of second value.``const` `bool` `comparator(``const` `pair<``int``,``int``>& p1, ``const` `pair<``int``,``int``>& p2)``{``    ``return` `(p1.second < p2.second);``}` `// Function for finding max length chain``int` `maxChainLen(vector >p, ``int` `n)``{``    ``// Initialize length l = 1``    ``int` `l = 1;` `    ``// Sort all pair in increasing order``    ``// according to second no of pair``    ``sort(p.begin(),p.end(),comparator);` `    ``// Pick up the first pair and assign the``    ``// value of second element fo pair to a``    ``// temporary variable s``    ``int` `s = p[0].second;` `    ``// Iterate from second pair (index of``    ``// the second pair is 1) to the last pair``    ``for` `(``int` `i = 1; i < n; i++) {` `        ``// If first of current pair is greater``        ``// than previously selected pair then``        ``// select current pair and update``        ``// value of l and s``        ``if` `(p[i].first > s) {``            ``l++;``            ``s = p[i].second;``        ``}``    ``}` `    ``// Return maximum length``    ``return` `l;``}` `// Driver Code``int` `main()``{` `    ``// Declaration of vector of pairs``    ``vector> p = { { 5, 24 }, { 39, 60 },``              ``{ 15, 28 }, { 27, 40 }, { 50, 90 } };` `    ``int` `n = p.size();` `    ``// Function call``    ``cout << maxChainLen(p, n) << endl;` `    ``return` `0;``}`

Java

 `// Java implementation of the above approach``import` `java.util.*;` `// Structure for storing pairs``// of first and second values.``class` `GFG{``    ` `// Class for storing pairs``// of first and second values.``static` `class` `Pair``{``    ``int` `first;``    ``int` `second;``    ` `    ``Pair(``int` `first, ``int` `second)``    ``{``        ``this``.first = first;``        ``this``.second = second;``    ``}``};``    ` `// Function for finding max length chain``static` `int` `maxChainLen(Pair p[], ``int` `n)``{``    ` `    ``// Initialize length l = 1``    ``int` `l = ``1``;` `    ``// Sort all pair in increasing order``    ``// according to second no of pair``    ``Arrays.sort(p, ``new` `Comparator()``    ``{``        ``public` `int` `compare(Pair a, Pair b)``        ``{``            ``return` `a.second - b.second;``        ``}``    ``});` `    ``// Pick up the first pair and assign the``    ``// value of second element fo pair to a``    ``// temporary variable s``    ``int` `s = p[``0``].second;` `    ``// Iterate from second pair (index of``    ``// the second pair is 1) to the last pair``    ``for``(``int` `i = ``1``; i < n; i++)``    ``{``        ` `        ``// If first of current pair is greater``        ``// than previously selected pair then``        ``// select current pair and update``        ``// value of l and s``        ``if` `(p[i].first > s)``        ``{``            ``l++;``            ``s = p[i].second;``        ``}``    ``}``    ` `    ``// Return maximum length``    ``return` `l;``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ` `    ``// Declaration of array of structure``    ``Pair p[] = ``new` `Pair[``5``];` `    ``p[``0``] = ``new` `Pair(``5``, ``24``);``    ``p[``1``] = ``new` `Pair(``39``, ``60``);``    ``p[``2``] = ``new` `Pair(``15``, ``28``);``    ``p[``3``] = ``new` `Pair(``27``, ``40``);``    ``p[``4``] = ``new` `Pair(``50``, ``90``);``    ` `    ``int` `n = p.length;``    ` `    ``// Function call``    ``System.out.println(maxChainLen(p, n));``}``}` `// This code is contributed by adityapande88`

C#

 `// C# implementation of the above approach``using` `System;``using` `System.Linq;` `// Structure for storing pairs``// of first and second values.``class` `GFG{``    ` `// Class for storing pairs``// of first and second values.``class` `Pair : IComparable``{``    ``public` `int` `first, second;``    ``public` `Pair(``int` `first, ``int` `second)``    ``{``        ``this``.first = first;``        ``this``.second = second;``    ``}``    ``public` `int` `CompareTo(Pair p)``    ``{``        ``return` `this``.second-p.second;``    ``}``}``    ` `// Function for finding max length chain``static` `int` `maxChainLen(Pair []p, ``int` `n)``{``    ` `    ``// Initialize length l = 1``    ``int` `l = 1;` `    ``// Sort all pair in increasing order``    ``// according to second no of pair``    ``Array.Sort(p);` `    ``// Pick up the first pair and assign the``    ``// value of second element fo pair to a``    ``// temporary variable s``    ``int` `s = p[0].second;` `    ``// Iterate from second pair (index of``    ``// the second pair is 1) to the last pair``    ``for``(``int` `i = 1; i < n; i++)``    ``{``        ` `        ``// If first of current pair is greater``        ``// than previously selected pair then``        ``// select current pair and update``        ``// value of l and s``        ``if` `(p[i].first > s)``        ``{``            ``l++;``            ``s = p[i].second;``        ``}``    ``}``    ` `    ``// Return maximum length``    ``return` `l;``}` `// Driver Code``public` `static` `void` `Main(String []args)``{``    ` `    ``// Declaration of array of structure``    ``Pair []p = ``new` `Pair[5];` `    ``p[0] = ``new` `Pair(5, 24);``    ``p[1] = ``new` `Pair(39, 60);``    ``p[2] = ``new` `Pair(15, 28);``    ``p[3] = ``new` `Pair(27, 40);``    ``p[4] = ``new` `Pair(50, 90);``    ` `    ``int` `n = p.Length;``    ` `    ``// Function call``    ``Console.WriteLine(maxChainLen(p, n));``}``}` `// This code is contributed by 29AjayKumar`

Python3

 `# Python3 implementation of the above approach`  `# Function for finding max length chain``def` `maxChainLen(p, n):``    ``# Initialize length l = 1``    ``l ``=` `1` `    ``# Sort all pair in increasing order``    ``# according to second no of pair``    ``p.sort(key``=``lambda` `x:x[``1``])` `    ``# Pick up the first pair and assign the``    ``# value of second element fo pair to a``    ``# temporary variable s``    ``s ``=` `p[``0``][``1``]` `    ``# Iterate from second pair (index of``    ``# the second pair is 1) to the last pair``    ``for` `i ``in` `range``(n):` `        ``# If first of current pair is greater``        ``# than previously selected pair then``        ``# select current pair and update``        ``# value of l and s``        ``if` `(p[i][``0``] > s) :``            ``l``+``=``1``            ``s ``=` `p[i][``1``]``        ` `    `  `    ``# Return maximum length``    ``return` `l`  `# Driver Code``if` `__name__ ``=``=` `'__main__'``:` `    ``# Declaration of vector of pairs``    ``p ``=` `[(``5``, ``24``) , (``39``, ``60``) ,``              ``(``15``, ``28``) , (``27``, ``40``) , (``50``, ``90``)] ` `    ``n ``=` `len``(p)` `    ``# Function call``    ``print``(maxChainLen(p, n))`
Output:
`3`

Time complexity : O(N*log(N))
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up