Maximum Length of Pair Chain

You are given an array of n pairs where pairs[i] = [left_i, right_i] and left_i < right_i. A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c, and a chain of pairs can be formed this way. Return the length of the longest chain which can be formed. You do not need to use up all the given pairs, and you can select pairs in any order.

30:00

Maximum Length of Pair Chain
medium
Free written solution
Topics
Companies

You are given an array of n pairs where pairs[i] = [left_i, right_i] and left_i < right_i. A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c, and a chain of pairs can be formed this way. Return the length of the longest chain which can be formed. You do not need to use up all the given pairs, and you can select pairs in any order.

Example 1:
Input: {"pairs":[[1,2],[2,3],[3,4]]}
Output: 2
Constraints:
  • n==pairs.lengthn == \text{pairs.length}

  • 1≤n≤10001 \leq n \leq 1000

  • −1000≤lefti<righti≤1000-1000 \leq \text{left}_i < \text{right}_i \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"pairs":[[1,2],[2,3],[3,4]]}

3 pair(s) on the number line. A pair can follow another only if it starts strictly after the other ends.

Pairs in input order

14[1,2][2,3][3,4]

+ starts after cur: joins chain

x overlaps cur: skipped

- - cur = end of chain

Chain so far: 0 pairs

(empty)

Variables
VariableValue
n3
DepthFunction Call
Stack empty
0/6