Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/646.html

646. Maximum Length of Pair Chain (Medium)

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

Related Topics:
Dynamic Programming

Similar Questions:

Solution 1. DP

First sort the array in ascending order.

Let dp[i] be the length of maximum chain formed using a subsequence of A[0..i] where A[i] must be used.

dp[i] = max(1, max(1 + dp[j] | pair j can go after pair i ))
// OJ: https://leetcode.com/problems/maximum-length-of-pair-chain/
// Time: O(N^2)
// Space: O(N)
class Solution {
public:
    int findLongestChain(vector<vector<int>>& A) {
        sort(begin(A), end(A));
        int N = A.size();
        vector<int> dp(N, 1);
        for (int i = 1; i < N; ++i) {
            for (int j = 0; j < i; ++j) {
                if (A[j][1] >= A[i][0]) continue;
                dp[i] = max(dp[i], 1 + dp[j]);
            }
        }
        return *max_element(begin(dp), end(dp));
    }
};

Solution 3. Interval Scheduling Maximization (ISM)

// OJ: https://leetcode.com/problems/maximum-length-of-pair-chain/
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
    int findLongestChain(vector<vector<int>>& A) {
        sort(begin(A), end(A), [](auto &a, auto &b) { return a[1] < b[1]; });
        int e = INT_MIN, ans = 0;
        for (auto &v : A) {
            if (e >= v[0]) continue;
            e = v[1];
            ++ans;
        }
        return ans;
    }
};
  • class Solution {
        public int findLongestChain(int[][] pairs) {
            Arrays.sort(pairs, new Comparator<int[]>() {
                public int compare(int[] pair1, int[] pair2) {
                    if (pair1[0] != pair2[0])
                        return pair1[0] - pair2[0];
                    else
                        return pair1[1] - pair2[1];
                }
            });
            int length = pairs.length;
            int[] dp = new int[length];
            Arrays.fill(dp, 1);
            for (int i = 1; i < length; i++) {
                int[] curPair = pairs[i];
                for (int j = 0; j < i; j++) {
                    int[] prevPair = pairs[j];
                    if (prevPair[1] < curPair[0])
                        dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            int max = 1;
            for (int num : dp)
                max = Math.max(max, num);
            return max;
        }
    }
    
    ############
    
    class Solution {
        public int findLongestChain(int[][] pairs) {
            Arrays.sort(pairs, Comparator.comparingInt(a -> a[1]));
            int ans = 0;
            int cur = Integer.MIN_VALUE;
            for (int[] p : pairs) {
                if (cur < p[0]) {
                    cur = p[1];
                    ++ans;
                }
            }
            return ans;
        }
    }
    
  • // OJ: https://leetcode.com/problems/maximum-length-of-pair-chain/
    // Time: O(N^2)
    // Space: O(N)
    class Solution {
    public:
        int findLongestChain(vector<vector<int>>& A) {
            sort(begin(A), end(A));
            int N = A.size();
            vector<int> dp(N, 1);
            for (int i = 1; i < N; ++i) {
                for (int j = 0; j < i; ++j) {
                    if (A[j][1] >= A[i][0]) continue;
                    dp[i] = max(dp[i], 1 + dp[j]);
                }
            }
            return *max_element(begin(dp), end(dp));
        }
    };
    
  • class Solution:
        def findLongestChain(self, pairs: List[List[int]]) -> int:
            ans, cur = 0, -inf
            for a, b in sorted(pairs, key=lambda x: x[1]):
                if cur < a:
                    cur = b
                    ans += 1
            return ans
    
    ############
    
    class Solution(object):
      def findLongestChain(self, pairs):
        """
        :type pairs: List[List[int]]
        :rtype: int
        """
        tails = []
        for start, end in sorted(pairs):
          idx = bisect.bisect_left(tails, start)
          if idx == len(tails):
            tails.append(end)
          else:
            tails[idx] = min(tails[idx], end)
        return len(tails)
    
    
  • func findLongestChain(pairs [][]int) int {
    	sort.Slice(pairs, func(i, j int) bool {
    		return pairs[i][1] < pairs[j][1]
    	})
    	ans, cur := 0, math.MinInt32
    	for _, p := range pairs {
    		if cur < p[0] {
    			cur = p[1]
    			ans++
    		}
    	}
    	return ans
    }
    
  • function findLongestChain(pairs: number[][]): number {
        pairs.sort((a, b) => a[1] - b[1]);
        let res = 0;
        let pre = -Infinity;
        for (const [a, b] of pairs) {
            if (pre < a) {
                pre = b;
                res++;
            }
        }
        return res;
    }
    
    
  • impl Solution {
        pub fn find_longest_chain(mut pairs: Vec<Vec<i32>>) -> i32 {
            pairs.sort_by(|a, b| a[1].cmp(&b[1]));
            let mut res = 0;
            let mut pre = i32::MIN;
            for pair in pairs.iter() {
                let a = pair[0];
                let b = pair[1];
                if pre < a {
                    pre = b;
                    res += 1;
                }
            }
            res
        }
    }
    
    

All Problems

All Solutions