Skip to content
Problem 646 · LeetCode 646(opens in a new tab)

Maximum Length of Pair Chain

MediumDynamic programming

You are given a list pairs, where each pair is [left, right] with left < right. Pair [c, d] can come right after pair [a, b] in a chain when b < c: the second pair has to start strictly after the first one ends.

Pick any of the pairs, in any order you like, and line them up into a chain. Return the largest number of pairs a chain can hold. You do not have to use every pair.

Example 1

Input:  pairs = [[7, 9], [1, 3], [2, 6], [4, 5], [8, 12]]
Output: 3
Why:    [1, 3] → [4, 5] → [7, 9]
2 more examples and the constraints

Example 2

Input:  pairs = [[1, 2], [2, 3]]
Output: 1
Why:    2 < 2 is false, so they cannot link

Example 3

Input:  pairs = [[-4, -1], [0, 3], [-2, 2]]
Output: 2
Why:    [-4, -1] → [0, 3]

Constraints

  • 1 ≤ number of pairs ≤ 1,000
  • −1,000 ≤ left < right ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort + DP over earlier pairsO(n²)
  2. Greedy by earliest endO(n log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 pairsVerdict
Sort + DPO(n²)
Passes; mention it as the LIS view
Greedy by earliest endO(n log n)
Best; one sort and one pass

n = number of pairs.

Edge cases to test

  • Touching ends. [1, 2] and [2, 3] do not chain: the rule is strict.
  • One pair. The answer is 1.
  • Identical pairs. Copies of one pair overlap, so only one can be used.
  • One long pair over short ones. [1, 10] with [2, 3], [4, 5], [6, 7] gives 3: the long pair is the one to drop.

Common mistakes

  • Sorting by start for the greedy, so a long early pair blocks shorter ones.
  • Using >= instead of >, which links pairs that share an end point.
  • Starting end at 0 instead of minus infinity, which wrongly skips pairs with negative starts.

How to talk through it

  1. 1Clarify. Is the rule b < c strictly? Can I reorder the pairs? Can values be negative?
  2. 2Give the DP. Sort by start; dp[i] is the best chain ending at i. Say it is O(n²).
  3. 3Spot the greedy. The pair that ends first is always a safe first pick; explain the swap argument.
  4. 4Code the one pass. Sort by end, track the last end, count the pairs you take.
  5. 5Test out loud. Run the touching-ends case and the long-pair-over-short-ones case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?