646. Maximum Length of Pair Chain

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:

  1. draw dp diagram(2d), but in this problem, dp is 1D.
    [[1,2],[1,3],[4,5],[2,3],[6,7]] dp diagram:


    image.png
  2. 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];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我拿到了一个对手公司报给客户的报价,于是我与客户联络,给到一个和对手相差不大,但是较低的价格。 然后我与客户联系,...
    victoriapoint阅读 283评论 0 0
  • 她坐着沙发,不停的调着台,慢慢的吸了口烟,我走过去问:晚上跟我一起吃饭么?她摇头,我:那你晚上吃饭么?她还摇头...
    Kimu阅读 131评论 0 1
  • 6. 柳家后院,柳老太君章氏正斜斜的侧靠在一个大迎枕上,闭目养神。昨日由于她多喝几杯大红袍,晚上就有点睡不着,今日...
    伊伊8899阅读 407评论 5 8
  • 场景1:国际漫游从来都是是非之地。最近就有个客户去了趟塞班,回来就整出了张1.6万元的“天价账单”。这类事情以前...
    小强快跑阅读 313评论 0 0
  • 好消息,大雪来啦!别激动,不是真的要下雪了,是“大雪”节气来了!可喜可贺的是:又是个喝酒的好日子。 汉口码头酒、纯...
    代锐锐阅读 430评论 0 0