Maximum Length of Pair Chain
Pattern: LIS family
Pair (c, d) can follow (a, b) when b < c. Sort pairs by their end and greedily take every pair that starts after the last chosen end: like activity selection.
The problem
Given pairs [left, right] with left < right, return the length of the longest chain where each pair's left is greater than the previous pair's right. Pairs may be used in any order.
Think first
- Which pair should start the chain?
- Why the earliest end?
- Is there a DP version?
Hints
Brute force, and why it fails
Sort by start and run an LIS-style DP: O(n²).
The key insight
Choosing the pair that ends earliest never hurts, so one greedy pass after sorting works.
Dry run
| count | 1 |
|---|
[[1, 2], [2, 3], [3, 4]], by end. Take [1, 2]; last end 2.
Step 1 of 2
The plan
sort by right
last = -inf
for (a, b): if a > last: count++, last = b
Complexity
- Time
O(n log n)- Space
O(1)
Sorting dominates.
Edge cases
- One pair: 1.
- Overlapping pairs.
- Touching ends do not chain.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int findLongestChain(int[][] pairs) {
int[][] p = pairs.clone();
Arrays.sort(p, (a, b) -> Integer.compare(a[1], b[1])); // by end: the earliest-ending pair leaves the most room
int count = 0;
long lastEnd = Long.MIN_VALUE;
for (int[] x : p) if (x[0] > lastEnd) { count++; lastEnd = x[1]; } // must start strictly after the last end
return count;
}
}C++
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
vector<vector<int>> p(pairs);
sort(p.begin(), p.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; }); // by end
int count = 0;
long long lastEnd = LLONG_MIN;
for (const vector<int>& x : p) if (x[0] > lastEnd) { count++; lastEnd = x[1]; } // must start after the last end
return count;
}
};Python
class Solution:
def findLongestChain(self, pairs: list[list[int]]) -> int:
count, last_end = 0, float("-inf")
for a, b in sorted(pairs, key=lambda p: p[1]): # by end: the earliest-ending pair leaves the most room
if a > last_end: # must start strictly after the last end
count += 1
last_end = b
return countCommon mistakes
- Sorting by start.
- Using
>=instead of>.