Sort the pairs by their end value. Always pick the next pair whose start is greater than the end of the last selected pair. This greedy approach ensures the longest chain.
Sort the pairs by their second value. Iterate through the sorted pairs, and for each, if its start is greater than the end of the last selected pair, increment the chain length and update the end.
classSolution {
public:int findLongestChain(vector<vector<int>>& pairs) {
sort(pairs.begin(), pairs.end(), [](constauto& a, constauto& b) { return a[1] < b[1]; });
int cur = INT_MIN, ans =0;
for (constauto& p : pairs) {
if (p[0] > cur) {
cur = p[1];
++ans;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
import"sort"funcfindLongestChain(pairs [][]int) int {
sort.Slice(pairs, func(i, jint) bool { returnpairs[i][1] < pairs[j][1] })
cur, ans:=-1<<31, 0for_, p:=rangepairs {
ifp[0] > cur {
cur = p[1]
ans++ }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
publicintfindLongestChain(int[][] pairs) {
Arrays.sort(pairs, (a, b) -> a[1]- b[1]);
int cur = Integer.MIN_VALUE, ans = 0;
for (int[] p : pairs) {
if (p[0]> cur) {
cur = p[1];
ans++;
}
}
return ans;
}
1
2
3
4
5
6
7
8
9
10
11
12
funfindLongestChain(pairs: Array<IntArray>): Int {
pairs.sortBy { it[1] }
var cur = Int.MIN_VALUE
var ans = 0for (p in pairs) {
if (p[0] > cur) {
cur = p[1]
ans++ }
}
return ans
}
1
2
3
4
5
6
7
8
9
classSolution:
deffindLongestChain(self, pairs: list[list[int]]) -> int:
pairs.sort(key=lambda x: x[1])
cur, ans = float('-inf'), 0for p in pairs:
if p[0] > cur:
cur = p[1]
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnfind_longest_chain(mut pairs: Vec<Vec<i32>>) -> i32 {
pairs.sort_by_key(|p| p[1]);
letmut cur =i32::MIN;
letmut ans =0;
for p in pairs {
if p[0] > cur {
cur = p[1];
ans +=1;
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
functionfindLongestChain(pairs: number[][]):number {
pairs.sort((a, b) =>a[1] -b[1]);
letcur=-Infinity, ans=0;
for (constpofpairs) {
if (p[0] >cur) {
cur=p[1];
ans++;
}
}
returnans;
}