From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- other/max_length_pair_chain.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 other/max_length_pair_chain.cpp (limited to 'other/max_length_pair_chain.cpp') diff --git a/other/max_length_pair_chain.cpp b/other/max_length_pair_chain.cpp new file mode 100644 index 0000000..c8ef536 --- /dev/null +++ b/other/max_length_pair_chain.cpp @@ -0,0 +1,33 @@ +// 646. Maximum Length of Pair Chain +#include "leetcode.h" + +/* + * given a n array of 'n' pairs, where 'pairs[i]= [lefti, righti]' and 'left[i] + * < right[i]'. 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 of the + * longest chain which can be formed. you do not need to use up all the given + * intervals. you can select pairs in any order. + */ + +class Solution { + static bool cmp(vector &a, vector &b) { return a[1] < b[1]; } + +public: + int findLongestChain(vvd & pairs) { + sort(pairs.begin(), pairs.end(), cmp); + int cnt = 0; + for (int i = 0, j = 0; j < pairs.size(); j++) + if (!j || pairs[i][1] < pairs[j][0]) { + cnt++; + i = j; + } + return cnt; + } +}; + +int main() { + Solution obj; + vvd p1 = {{1, 2}, {2, 3}, {3, 4}}, p2 = {{1, 2}, {7, 8}, {4, 5}}; + printf("%d\n", obj.findLongestChain(p1)); // expect: 2 + printf("%d\n", obj.findLongestChain(p2)); // expect: 3 +} -- cgit v1.2.3