646. Maximum Length of Pair Chain
You are given n
pairs of numbers. In every pair, the first number is always smaller than the second number.
Now, we define a pair (c, d)
can follow another pair (a, b)
if and only if b < c
. Chain of pairs can be formed in this fashion.
Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order.
Example 1:
Input: [[1,2], [2,3], [3,4]] Output: 2 Explanation: The longest chain is [1,2] -> [3,4]
Note:
- The number of given pairs will be in the range [1, 1000].
Rust Solution
struct Solution;
impl Solution {
fn find_longest_chain(mut pairs: Vec<Vec<i32>>) -> i32 {
let n = pairs.len();
pairs.sort_by_key(|p| p[1]);
let mut res = 0;
let mut cur = std::i32::MIN;
for i in 0..n {
if cur < pairs[i][0] {
cur = pairs[i][1];
res += 1;
}
}
res as i32
}
}
#[test]
fn test() {
let pairs = vec_vec_i32![[1, 2], [2, 3], [3, 4]];
let res = 2;
assert_eq!(Solution::find_longest_chain(pairs), res);
}
Having problems with this solution? Click here to submit an issue on github.