[LeetCode] Maximum Length of Pair Chain

646. Maximum Length of Pair Chain

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
vector<pair<int,int>> p, rp;
int n = pairs.size();
for(int i = 0; i < n; i++) {
p.push_back({pairs[i][0], i});
rp.push_back({pairs[i][1], i});
}
sort(begin(p), end(p));
sort(begin(rp), end(rp));

vector<int> dp(n, 1);
int res = 1;
for(int i = 0; i < n; i++) {
for(int j = 0; rp[j].first < p[i].first; j++) {
dp[p[i].second] = max(dp[p[i].second], dp[rp[j].second] + 1);
res = max(res, dp[p[i].second]);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/24/PS/LeetCode/maximum-length-of-pair-chain/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.