Maximum Length of Pair Chain LeetCode Solution

Here, We see Maximum Length of Pair Chain LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Maximum Length of Pair Chain LeetCode Solution

Maximum Length of Pair Chain LeetCode Solution

Problem Statement

You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.

A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.

Return the length longest chain which can be formed.

You do not need to use up all the given intervals. You can select pairs in any order.

Example 1:
Input: pairs = [[1,2],[2,3],[3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4].

Example 2:
Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3
Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].

Maximum Length of Pair Chain LeetCode Solution C++

class Solution {
public:
    int findLongestChain(vector<vector<int>>& pairs) {
        sort(pairs.begin(), pairs.end(), [](const vector<int>& a, const vector<int>& b) {
            return a[1] < b[1];
        });
        int cur = INT_MIN, ans = 0;
        for (const auto& pair : pairs) {
            if (cur < pair[0]) {
                cur = pair[1];
                ans++;
            }
        }
        return ans;        
    }
};Code language: PHP (php)

Maximum Length of Pair Chain Solution Java

class Solution {
    public int findLongestChain(int[][] pairs) {
        Arrays.sort(pairs, (a, b) -> Integer.compare(a[1], b[1]));
        int cur = Integer.MIN_VALUE, ans = 0;
        for (int[] pair : pairs) {
            if (cur < pair[0]) {
                cur = pair[1];
                ans++;
            }
        }
        return ans;        
    }
}Code language: PHP (php)

Maximum Length of Pair Chain Solution JavaScript

var findLongestChain = function(pairs) {
    pairs.sort((a, b) => a[1] - b[1]);
    let cur = Number.MIN_SAFE_INTEGER, ans = 0;
    for (const [start, end] of pairs) {
        if (cur < start) {
            cur = end;
            ans++;
        }
    }
    return ans;    
};Code language: JavaScript (javascript)

Maximum Length of Pair Chain Solution Python

class Solution(object):
    def findLongestChain(self, pairs):
        pairs.sort(key=lambda x: x[1])
        cur, ans = float('-inf'), 0
        for pair in pairs:
            if cur < pair[0]:
                cur = pair[1]
                ans += 1      
        return ansCode language: HTML, XML (xml)
Scroll to Top