LeetCode 646. Maximum Length of Pair Chain

原题链接在这里:https://leetcode.com/problems/maximum-length-of-pair-chain/description/

题目:

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:

  1. The number of given pairs will be in the range [1, 1000].

题解:

Sort pairs first based on first element.

Use dp array, dp[i] means up to i, the maximum length of chain. For all j from 0 to i-1, if pairs[j][1] < pairs[i][0], dp[i] = Math.max(dp[i], dp[j]+1).

Time Complexity: O(n^2). n = pairs.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int findLongestChain(int[][] pairs) {
 3         if(pairs == null || pairs.length == 0){
 4             return 0;
 5         }
 6         
 7         
 8         Arrays.sort(pairs, (a, b)->a[0]==b[0] ? a[1]-b[1] : a[0]-b[0]);
 9         
10         int n = pairs.length;
11         int [] dp = new int[n];
12         for(int i = 0; i<n; i++){
13             dp[i] = 1;
14             for(int j = 0; j<i; j++){
15                 if(pairs[j][1]<pairs[i][0]){
16                     dp[i] = Math.max(dp[i], dp[j]+1);
17                 }
18             }
19         }
20         
21         return dp[n-1];
22     }
23 }

按照pair的second number 排序pairs. 再iterate pairs, 若当前pair的second number 小于下个pair的first number, 计数res++, 否则跳过下个pair.

Note: 用curEnd把当前的second number标记出来, 不要用pair[i][1], 否则 i 跳动时就不是当前pair的second number了.

Time Complexity: O(nlogn). n = pairs.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int findLongestChain(int[][] pairs) {
 3         Arrays.sort(pairs, (a,b) -> a[1]-b[1]);
 4         int res = 0;
 5         int curEnd = Integer.MIN_VALUE;
 6         for(int [] pair : pairs){
 7             if(pair[0] > curEnd){
 8                 res++;
 9                 curEnd = pair[1];
10             }
11         }
12         
13         return res;
14     }
15 }

类似Longest Increasing Subsequence.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7584319.html