Maximum Length Chain of Pairs | Set | Java implementation of the above approach ; Structure for storing pairs of first and second values . ; Class for storing pairs of first and second values . ; Function for finding max length chain ; Initialize length l = 1 ; Sort all pair in increasing order according to second no of pair ; Pick up the first pair and assign the value of second element fo pair to a temporary variable s ; Iterate from second pair ( index of the second pair is 1 ) to the last pair ; If first of current pair is greater than previously selected pair then select current pair and update value of l and s ; Return maximum length ; Driver Code ; Declaration of array of structure ; Function call
import java . util . * ; class GFG { static class Pair { int first ; int second ; Pair ( int first , int second ) { this . first = first ; this . second = second ; } } ; static int maxChainLen ( Pair p [ ] , int n ) { int l = 1 ; Arrays . sort ( p , new Comparator < Pair > ( ) { public int compare ( Pair a , Pair b ) { return a . second - b . second ; } } ) ; int s = p [ 0 ] . second ; for ( int i = 1 ; i < n ; i ++ ) { if ( p [ i ] . first > s ) { l ++ ; s = p [ i ] . second ; } } return l ; } public static void main ( String args [ ] ) { 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 ; System . out . println ( maxChainLen ( p , n ) ) ; } }