|
| 1 | +package greedy; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by gouthamvidyapradhan on 01/05/2018. |
| 7 | + * You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. |
| 8 | +
|
| 9 | + Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. |
| 10 | + Chain of pairs can be formed in this fashion. |
| 11 | +
|
| 12 | + Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. |
| 13 | + You can select pairs in any order. |
| 14 | +
|
| 15 | + Example 1: |
| 16 | + Input: [[1,2], [2,3], [3,4]] |
| 17 | + Output: 2 |
| 18 | + Explanation: The longest chain is [1,2] -> [3,4] |
| 19 | + Note: |
| 20 | + The number of given pairs will be in the range [1, 1000]. |
| 21 | +
|
| 22 | + Solution: O(N log N) sort the pairs with ending interval (greedy sort) and try to accommodate as many pairs |
| 23 | + as possible. If any current pair violates the chaining condition (b < c) then, ignore that particular pair. |
| 24 | + */ |
| 25 | +public class MaximumLengthOfPairChain { |
| 26 | + |
| 27 | + /** |
| 28 | + * Main method |
| 29 | + * @param args |
| 30 | + * @throws Exception |
| 31 | + */ |
| 32 | + public static void main(String[] args) throws Exception{ |
| 33 | + int[][] A = {{1,2}, {2,3}, {3,4}}; |
| 34 | + System.out.println(new MaximumLengthOfPairChain().findLongestChain(A)); |
| 35 | + } |
| 36 | + |
| 37 | + public int findLongestChain(int[][] pairs) { |
| 38 | + Arrays.sort(pairs, (o1, o2) -> o1[1] == o2[1] ? Integer.compare(o1[0], o2[0]) : Integer.compare(o1[1], o2[1])); |
| 39 | + int count = 1; |
| 40 | + int[] curr = pairs[0]; |
| 41 | + for(int i = 1; i < pairs.length; i ++){ |
| 42 | + if(pairs[i][0] > curr[1]){ |
| 43 | + count++; |
| 44 | + curr = pairs[i]; |
| 45 | + } |
| 46 | + } |
| 47 | + return count; |
| 48 | + } |
| 49 | + |
| 50 | +} |
0 commit comments