Maximum Length of Pair Chain - Problem
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 of the longest chain which can be formed. You do not need to use up all the given intervals. You can select pairs in any order.
Input & Output
Example 1 — Basic Chain
$
Input:
pairs = [[1,2],[2,3],[3,4]]
›
Output:
2
💡 Note:
The longest chain is [1,2] → [3,4]. We can't use [2,3] because 2 is not less than 2.
Example 2 — All Can Chain
$
Input:
pairs = [[1,2],[7,8],[4,5]]
›
Output:
3
💡 Note:
After sorting by end time: [1,2] → [4,5] → [7,8]. All pairs can form a valid chain.
Example 3 — No Chaining Possible
$
Input:
pairs = [[1,4],[2,3]]
›
Output:
1
💡 Note:
Cannot chain [1,4] → [2,3] because 4 ≥ 2. Maximum chain length is 1.
Constraints
- n == pairs.length
- 1 ≤ n ≤ 1000
- -1000 ≤ lefti < righti ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code