Maximum Length of Pair Chain - Problem
You're given an array of n pairs where each pair is represented as pairs[i] = [left_i, right_i] with left_i < right_i.
A pair p2 = [c, d] can follow a pair p1 = [a, b] if b < c (the right value of the first pair is strictly less than the left value of the second pair).
Your goal is to form the longest possible chain of pairs following this rule. You can select pairs in any order and don't need to use all pairs.
Example:
Input: [[1,2], [2,3], [3,4]]
Output: 2 (chain: [1,2] โ [3,4])
Note: [2,3] cannot follow [1,2] since 2 is not less than 2
Input & Output
example_1.py โ Basic Chain
$
Input:
pairs = [[1,2], [2,3], [3,4]]
โบ
Output:
2
๐ก Note:
The longest chain is [1,2] โ [3,4]. Note that [2,3] cannot follow [1,2] because 2 is not strictly less than 2.
example_2.py โ Multiple Valid Chains
$
Input:
pairs = [[1,2], [7,8], [4,5]]
โบ
Output:
3
๐ก Note:
All pairs can be chained together: [1,2] โ [4,5] โ [7,8], giving us a chain of length 3.
example_3.py โ Single Pair
$
Input:
pairs = [[1,3]]
โบ
Output:
1
๐ก Note:
With only one pair, the maximum chain length is 1.
Visualization
Tap to expand
Understanding the Visualization
1
Sort by End Time
Arrange all meetings by when they end - this is key to the greedy strategy
2
Pick Earliest Ending
Always select the meeting that ends earliest among available options
3
Check Compatibility
Only book meetings that start after the previous one completely ends
4
Maximize Bookings
This greedy choice leads to the maximum number of scheduled meetings
Key Takeaway
๐ฏ Key Insight: Sorting by end time and using a greedy approach guarantees the maximum chain length because it always preserves the most opportunities for future selections.
Time & Space Complexity
Time Complexity
O(2^n * n!)
2^n subsets, each potentially requiring n! permutations to check
โ Quadratic Growth
Space Complexity
O(n)
Space for recursion stack and storing current chain
โก Linearithmic Space
Constraints
- 1 โค n โค 1000 where n is the length of pairs
- -1000 โค lefti < righti โค 1000
- lefti < righti for all pairs
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code