Maximum Length of Pair Chain
Master this topic with zero to advance depth.
Maximum Length of Pair Chain
You are given an array of n pairs pairs where pairs[i] = [left_i, right_i] and left_i < right_i.
A pair p2 follows p1 if p1[1] < p2[0]. Return the length of the longest chain.
Visual Representation
Pairs: [[1,2], [7,8], [4,5]]
1. Sort by end points: [1,2], [4,5], [7,8]
2. Chain: [1,2] -> [4,5] -> [7,8]
Length: 3Examples
Longest chain: [1,2] -> [3,4]. Note: [2,3] cannot follow [1,2] because 2 is not < 2.
Level I: Brute Force (Recursive Backtracking)
Intuition
Try all possible subsequences of pairs and check if they form a valid chain. To optimize slightly, we can first sort by start time and use recursion with a 'pick or skip' strategy.
Thought Process
solve(idx, prevEnd)- For each pair
idx:- If
pairs[idx].start > prevEnd, we can pick it:1 + solve(idx + 1, pairs[idx].end). - We can always skip it:
solve(idx + 1, prevEnd).
- If
- Return the maximum of both.
Detailed Dry Run
pairs = [[1,2], [2,3], [3,4]]
- solve(0, -inf): Pick [1,2] -> solve(1, 2) -> Pick [3,4] -> SUCCESS (2 pairs)
- solve(0, -inf): Skip [1,2] -> solve(1, -inf) -> Pick [2,3] -> solve(2, 3) -> Pick [3,4] (FAIL: 3 not > 3)
Level II: Dynamic Programming (LIS Variation)
Intuition
This problem is perfectly analogous to Longest Increasing Subsequence (LIS). We want to find the longest chain where each pair follows the previous one.
Thought Process
- Sort the pairs by their start element.
- Initialize a
dparray wheredp[i]is the length of the longest chain ending at indexi(initially all 1). - For each
i, check allj < i: ifpairs[j].end < pairs[i].start, thendp[i] = max(dp[i], dp[j] + 1).
Pattern: Dynamic Programming / LIS
Detailed Dry Run
pairs = [[1,2], [2,3], [3,4]], dp=[1, 1, 1]
- i=1 ([2,3]): j=0 ([1,2]). 2 is not > 2. dp[1]=1.
- i=2 ([3,4]): j=0 ([1,2]). 3 > 2. dp[2]=max(1, dp[0]+1)=2.
- i=2 ([3,4]): j=1 ([2,3]). 3 is not > 3. dp[2]=2. Max dp = 2.
Level III: Optimal Greedy (Interval Scheduling-Style)
Intuition
To fit the maximum number of intervals into a chain, we should always pick the pair that ends the earliest. This leaves the maximum room for subsequent pairs.
Thought Process
- Sort pairs by their end element
pair[1]. - Maintain
currEndof the chain. - For each pair, if its
start > currEnd, add it to the chain and updatecurrEnd.
Pattern: Interval Selection / Activity Selection
Detailed Dry Run
pairs = [[1,2], [7,8], [4,5]] Sorted by end: [[1,2], [4,5], [7,8]]
| Pair | currEnd | Action |
|---|---|---|
| [1,2] | 2 | Pick [1,2], count=1 |
| [4,5] | 5 | 4 > 2? YES. Pick [4,5], count=2 |
| [7,8] | 8 | 7 > 5? YES. Pick [7,8], count=3 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.