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].
Another classic dp problem:
-
draw dp diagram(2d), but in this problem, dp is 1D.
[[1,2],[1,3],[4,5],[2,3],[6,7]] dp diagram:
- Be careful of [-9,10], this kind of pairs that cover all range, which may cause the first row become 1: dp[0] = 1. So stay with last max is very important.
class Solution {
public int findLongestChain(int[][] pairs) {
// 0 and null
if(pairs==null||pairs.length == 0) return 0;
int n = pairs.length;
int[] dp = new int[n];
// In java 8.0, sort array by first element. because pairs is unsorted
Arrays.sort(pairs, (a, b) -> (a[0] - b[0]));
for(int i=n-1;i>=0;i--){
dp[i]=1;
for(int j = i+1;j<n;j++){
// if find a smaller pair +1, else stay with last max
if(pairs[j][0]>pairs[i][1]) dp[i] = Math.max(dp[j]+1,dp[i]);
else dp[i] = Math.max(dp[i],dp[j]);
// dp[i] = Math.max(dp[i], pairs[i][0] > pairs[j][1]? dp[j] + 1 : dp[j]);
}
}
return dp[0];
}
}