646. Maximum Length of Pair Chain
Description
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
. A chain of pairs can be formed in this fashion.
Return the length longest chain which can be formed.
You do not need to use up all the given intervals. You can select pairs in any order.
Example 1:
Input: pairs = [[1,2],[2,3],[3,4]] Output: 2 Explanation: The longest chain is [1,2] -> [3,4].
Example 2:
Input: pairs = [[1,2],[7,8],[4,5]] Output: 3 Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].
Constraints:
n == pairs.length
1 <= n <= 1000
-1000 <= lefti < righti <= 1000
Solution
maximum-length-of-pair-chain.py
class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort(key = lambda x: x[1])
res = 1
s, e = pairs[0]
for start, end in pairs[1:]:
if e >= start: continue
s, e = start, end
res += 1
return res
maximum-length-of-pair-chain.java
class Solution {
public int findLongestChain(int[][] pairs) {
int n = pairs.length;
if (pairs == null || n == 0) return 0;
Arrays.sort(pairs, (a, b) -> (a[0] - b[0]));
int[] dp = new int[n];
Arrays.fill(dp, 1);
for (int i = 0; i < n; i++){
for (int j = 0; j < i; j++){
dp[i] = Math.max(dp[i], pairs[i][0] > pairs[j][1] ? dp[j] + 1 : dp[j]);
}
}
return dp[n-1];
}
}