Maximum Length of Pair Chain
Problem
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.
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.
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.
Example 1:
Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]
Note: The number of given pairs will be in the range [1, 1000].
Solution
Sort by End Solution: O(nlgn) time, O(1) space
public class Solution {
public int findLongestChain(int[][] pairs) {
Arrays.sort(pairs, (a, b) -> a[1] - b[1]);
int i = 0, res = 0;
while (i < pairs.length) {
res++;
int curEnd = pairs[i][1];
while (i + 1 < pairs.length && pairs[i + 1][0] <= curEnd) i++;
i++;
}
return res;
}
}
Analysis
This is a pretty easy problem as long as we sort the given pairs
by their ends
We know that the longest pair chains must starts from the pair
with smallest end (proved by contradiction)
Therefore, starting from the first smallest end, we pass the pairs whose start is smaller or equal to curEnd
We also need to increment the i
and res
when while
loop starts and reaches the end