Maximum Length of Pair Chain — LeetCode 646 Python Solution
MediumGreedyArrayDynamic ProgrammingSorting
- Problem
- #646
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti. A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c.
Example
- Input
- pairs = [[1,2],[2,3],[3,4]]
- Output
- 2
- Explanation
- The longest chain is [1,2] -> [3,4].
Python solution
Python
class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort(key=lambda x: x[1])
ans, pre = 0, -inf
for a, b in pairs:
if pre < a:
ans += 1
pre = b
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 646. Maximum Length of Pair Chain is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 646. Maximum Length of Pair Chain?
- LeetCode 646. Maximum Length of Pair Chain is rated Medium on LeetCode.
- What is the time complexity of LeetCode 646. Maximum Length of Pair Chain?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 646. Maximum Length of Pair Chain?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 646. Maximum Length of Pair Chain cover?
- LeetCode 646. Maximum Length of Pair Chain is tagged Greedy, Array, Dynamic Programming and Sorting on LeetCode.