LeetCode 646. Maximum Length of Pair Chain

原題連接在這裏:https://leetcode.com/problems/maximum-length-of-pair-chain/description/html

題目:post

You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.this

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.url

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.spa

Example 1:code

Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]

Note:orm

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

題解:htm

Sort pairs first based on first element.blog

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.

相關文章
相關標籤/搜索