|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * 646. Maximum Length of Pair Chain |
| 7 | + * |
| 8 | + * You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. |
| 9 | +
|
| 10 | + Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. 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. You can select pairs in any order. |
| 13 | +
|
| 14 | + Example 1: |
| 15 | + Input: [[1,2], [2,3], [3,4]] |
| 16 | + Output: 2 |
| 17 | + Explanation: The longest chain is [1,2] -> [3,4] |
| 18 | +
|
| 19 | + Note: |
| 20 | + The number of given pairs will be in the range [1, 1000]. |
| 21 | + */ |
| 22 | +public class _646 { |
| 23 | + |
| 24 | + /**credit: https://discuss.leetcode.com/topic/96804/java-o-nlog-n-time-o-1-space*/ |
| 25 | + public int findLongestChain(int[][] pairs) { |
| 26 | + Arrays.sort(pairs, (o1, o2) -> o1[1] - o2[1]); |
| 27 | + int result = 0; |
| 28 | + int n = pairs.length; |
| 29 | + int i = -1; |
| 30 | + while (++i < n) { |
| 31 | + result++; |
| 32 | + int curEnd = pairs[i][1]; |
| 33 | + while (i+1 < n && pairs[i+1][0] <= curEnd) { |
| 34 | + /**This means, we'll keep incrementing i until pairs[i+1][0] is |
| 35 | + * exactly greater than curEnd.*/ |
| 36 | + i++; |
| 37 | + } |
| 38 | + } |
| 39 | + return result; |
| 40 | + } |
| 41 | + |
| 42 | + public static void main(String... args) { |
| 43 | + _646 test = new _646(); |
| 44 | + |
| 45 | +// int[][] pairs = new int[][]{ |
| 46 | +// {1,2}, |
| 47 | +// {2,3}, |
| 48 | +// {5,6}, |
| 49 | +// {3,4} |
| 50 | +// }; |
| 51 | + |
| 52 | + int[][] pairs = new int[][]{ |
| 53 | + {9,10}, |
| 54 | + {-9,9}, |
| 55 | + {-6,1}, |
| 56 | + {-4,1}, |
| 57 | + {8,10}, |
| 58 | + {7,10}, |
| 59 | + {9,10}, |
| 60 | + {2,10} |
| 61 | + }; |
| 62 | + |
| 63 | + int i = test.findLongestChain(pairs); |
| 64 | + System.out.println(i); |
| 65 | + System.out.println("Hello World!"); |
| 66 | + } |
| 67 | +} |
0 commit comments