




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.
1import java.util.*;
2
3public class PairChain {
4    public static int findLongestChain(int[][] pairs) {
5        Arrays.sort(pairs, Comparator.comparingInt(a -> a[1]));
6        int currentEnd = Integer.MIN_VALUE, count = 0;
7        for (int[] pair : pairs) {
8            if (pair[0] > currentEnd) {
9                currentEnd = pair[1];
10                count++;
11            }
12        }
13        return count;
14    }
15
16    public static void main(String[] args) {
17        int[][] pairs = {{1, 2}, {2, 3}, {3, 4}};
18        System.out.println(findLongestChain(pairs));
19    }
20}In Java, this solution sorts the array of pairs using a lambda expression for comparing the second elements. It uses a greedy approach to determine the maximum length of a chain that can be formed.
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.
1def
The Python implementation constructs the dp array initialized to 1. It sorts the pairs by their first element and fills in dp based on possible chains, ultimately determining the maximum length.