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閱讀 281評論 0 0
  • 她坐著沙發,不停的調著臺,慢慢的吸了口煙,我走過去問:晚上跟我一起吃飯么?她搖頭,我:那你晚上吃飯么?她還搖頭...
    Kimu閱讀 128評論 0 1
  • 6. 柳家后院,柳老太君章氏正斜斜的側靠在一個大迎枕上,閉目養神。昨日由于她多喝幾杯大紅袍,晚上就有點睡不著,今日...
    伊伊8899閱讀 402評論 5 8
  • 場景1:國際漫游從來都是是非之地。最近就有個客戶去了趟塞班,回來就整出了張1.6萬元的“天價賬單”。這類事情以前...
    小強快跑閱讀 308評論 0 0
  • 好消息,大雪來啦!別激動,不是真的要下雪了,是“大雪”節氣來了!可喜可賀的是:又是個喝酒的好日子。 漢口碼頭酒、純...
    代銳銳閱讀 412評論 0 0