Max length chain | Practice | GeeksforGeeks

You are given N pairs of numbers. 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. Chain of pairs can be formed in this fashion. You have to find the longest chain which can be formed from the given set of pairs. 
 
Example 1:
Input:
N = 5
P[] = {5  24 , 39 60 , 15 28 , 27 40 , 50 90}
Output: 3
Explanation: The given pairs are { {5, 24}, {39, 60},
{15, 28}, {27, 40}, {50, 90} },the longest chain that
can be formed is of length 3, and the chain is
{{5, 24}, {27, 40}, {50, 90}}


â€‹Example 2:
Input:
N = 2
P[] = {5 10 , 1 11}
Output: 1
Explanation:The max length chain possible is only of
length one.

 
Your Task:
You don't need to read input or print anything. Your task is to Complete the function maxChainLen() which takes a structure p[] denoting the pairs and n as the number of pairs and returns the length of the longest chain formed.
 
Expected Time Complexity: O(N*N)
Expected Auxiliary Space: O(N)

Constraints:
1<=N<=100
0
tsachin7351 day ago
C++ SOLUTION
bool mycomp(struct val &a , struct val &b){   return a.second<b.second;}
int maxChainLen(struct val p[],int n){ sort(p , p+n , mycomp); int previous=0; int count =1; for(int current =1 ; current<n ; current++){     if(p[previous].second<p[current].first){         previous = current;         count++;     } } return count ; }
 
 
+2
sanketbhagat1 week ago
SIMPLE JAVA SOLUTION
class GfG{
    int maxChainLength(Pair arr[], int n){
       // your code here
       Arrays.sort(arr,(a,b)->a.y-b.y);
       int dp[] = new int[n];
       Arrays.fill(dp,1);
       int ans = 0;
       for(int i=0;i<n;i++){
           for(int j=0;j<i;j++){
               if(arr[i].x>arr[j].y) dp[i] = Math.max(dp[i],1+dp[j]);
           }
           ans = Math.max(ans,dp[i]);
       }
       return ans;
    }
}
0
sagrikasoni2 weeks ago
JAVA Solution (Greedy Approach)
class GfG
{
    int maxChainLength(Pair arr[], int n)
    {
      Arrays.sort(arr,(a,b)->a.y-b.y);
      int count =1;
      int  end = arr[0].y;
   for(int i =1;i<n;i++){
          if(end<arr[i].x){
              count++;
              end = arr[i].y;
              }
      }
      return count;
    }
}
0
keshav_bhaau2 weeks ago
LIS + Sorting (overall, O(Nlogn)):
int maxChainLen(struct val arr[],int n)
{
    sort(arr, arr+n ,[](val &a, val &b){
        return a.first<b.first;
    });                        
    vector<int> dp;
    dp.push_back(arr[0].second);
    
    for(int i=1;i<n;i++)
    {
        if(arr[i].first>dp.back())
            dp.push_back(arr[i].second);
        else{
            int index= lower_bound(dp.begin(), dp.end(), arr[i].second)-dp.begin();
            dp[index]= arr[i].second;
        }
    }
    return dp.size();
    
}
0
jainmuskan5653 weeks ago
int solve(int prev,int curr, struct val p[],int n, vector<vector<int>> & dp){   // LIS plus sorting   if(curr==n){       return 0;   }   if(dp[prev+1][curr] > -1){       return dp[prev+1][curr];   }   int len= solve(prev,curr+1,p,n,dp);   if(prev==-1 || p[prev].second < p[curr].first){       len=max(len,1+solve(curr,curr+1,p,n,dp));   }   return dp[prev+1][curr]= len;}static bool comp(struct val a,struct val b){   return a.second<b.second;}int maxChainLen(struct val p[],int n){   vector<vector<int>> dp(n+1,vector<int>(n+1,-1));   // sort p   sort(p,p+n, comp);   return solve(-1,0,p,n,dp);}
0
cyrus184 weeks ago
Java Solution 
class GfG
{
    int maxChainLength(Pair arr[], int n)
    {
       // your code here
       Arrays.sort(arr, (a, b) -> (a.y - b.y));
       int[] dp=new int[n];
       Arrays.fill(dp, 1);
       int res=1;
       for(int i=1;i<n;i++){
           for(int j=0;j<i;j++){
               if(arr[i].x > arr[j].y)
                    dp[i]=Math.max(dp[i], dp[j]+1);
                res=Math.max(res , dp[i]);
           }
       }
       return res;
    }
}
0
kuldeepy104591 month ago
 bool sortbysecond(struct val &a,struct val &b){     return a.second<b.second;}int maxChainLen(struct val p[],int n){//Your code heresort(p,p+n,sortbysecond);vector<int>output(n);output[0]=1;for(int i=1;i<n;i++){    output[i]=1;    for(int j=i-1;j>=0;j--){         if(p[i].first<=p[j].second){             continue;         }         int possible=output[j]+1;         if(possible>output[i]){             output[i]=possible;                      }    }}int max= *max_element(output.begin(),output.end());return max; 
}
0
hamidnourashraf2 months ago
def maxChainLen(Parr, n):
    sorted_parr = sorted(Parr, key=lambda x: x.b)
    _max = 0
    for i in range(n):
        cnt = 1
        curr_b = sorted_parr[i].b
        for j in range(i+1, n):
            if sorted_parr[j].a > curr_b:
                curr_b = sorted_parr[j].b
                cnt += 1
        _max = max(_max, cnt)
    return _max
0
junaidalthaf2 months ago
Why are we expected to sort the pair list?
+1
sknwd88642 months ago
static bool compare(struct val& a, struct val& b)
{
    return a.first < b.first;
}

int maxChainLen(struct val arr[], int n)
{
    sort(arr, arr + n, compare);
    
    vector<int> dp(n, 1);
    
    for(int i = 1; i < n; i++)
    {
        for(int j = 0; j < i; j++)
        {
            if(arr[j].second < arr[i].first && dp[j] + 1 > dp[i])
            {
                dp[i] = dp[j] + 1;
            }
        }
    }
    
    return *max_element(dp.begin(), dp.end());
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.