




Sponsored
Sponsored
This approach involves sorting the pairs by their second element and then greedily selecting pairs that can extend the chain. The intuition here is that by picking the pairs with the smallest possible ending, we maintain maximum flexibility for extending the chain.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) as it sorts in-place.
1#include <vector>
2#include <algorithm>
3#include <iostream>
4
5int findLongestChain(std::vector<std::vector<int>>& pairs) {
6    std::sort(pairs.begin(), pairs.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
7        return a[1] < b[1];
8    });
9    int currentEnd = INT_MIN, count = 0;
10    for (const auto& pair : pairs) {
11        if (pair[0] > currentEnd) {
12            currentEnd = pair[1];
13            count++;
14        }
15    }
16    return count;
17}
18
19int main() {
20    std::vector<std::vector<int>> pairs = {{1,2},{2,3},{3,4}};
21    std::cout << findLongestChain(pairs) << std::endl;
22    return 0;
23}The C++ solution leverages STL's sort function to arrange the pairs based on the second element. It then uses a greedy algorithm to count the longest valid chain of pairs.
This approach uses dynamic programming to determine the longest chain. We first sort the pairs based on the first element. Then, we define a DP array where dp[i] represents the length of the longest chain ending with the i-th pair.
Time Complexity: O(n^2)
Space Complexity: O(n) due to the DP array.
1#
The C implementation initializes a DP array with 1, as each pair can be a chain of length 1. It sorts the pairs by the first element, then uses nested loops to populate the DP table, calculating the maximum length for each position.