leetcode - 646. Maximum Length of Pair Chain

Description

You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.

A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.

Return the length longest chain which can be formed.

You do not need to use up all the given intervals. You can select pairs in any order.

Example 1:

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

Example 2:

Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3
Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].

Constraints:

n == pairs.length
1 <= n <= 1000
-1000 <= lefti < righti <= 1000

Solution

DP

Use dp[i] to denote the longest length that ends with pairs[i], then transformation equation is:
d p [ i ] = { 1 + d p [ i − 1 ] ,      if pairs[i] and pairs[i - 1] don’t overlap max ⁡ ( d p [ i − 1 ] , 1 + d p [ k ] ) ,      else dp[i] = \begin{cases}\begin{aligned} 1 + dp[i - 1], \;\; &\text{if pairs[i] and pairs[i - 1] don't overlap} \\ \max(dp[i-1], 1 + dp[k]),\;\; &\text{else} \end{aligned}\end{cases} dp[i]={1+dp[i1],max(dp[i1],1+dp[k]),if pairs[i] and pairs[i - 1] don’t overlapelse
where k is the last index of the interval that doesn’t overlap with i

We could sort pairs by the end to use binary search, so the time complexity for searching would be log ⁡ n \log n logn
Time complexity: o ( n log ⁡ n ) o(n \log n) o(nlogn)
Space complexity: o ( n ) o(n) o(n)

Greedy

By greedy, we think the interval with shorter end is always better, no matter what the start is like. Because by selecting the shorter end interval, we always have higher probability for next intervals.

So sort the intervals by end, then iterate from left to right, if the current interval could fit, then fit, else keep iterating.

Time complexity: o ( n log ⁡ n + n ) o(n \log n + n) o(nlogn+n), n log ⁡ n n \log n nlogn for sorting, n n n for iterating
Space complexity: o ( 1 ) o(1) o(1)

Code

dp

class Solution:
    def findLongestChain(self, pairs: List[List[int]]) -> int:
        pairs.sort(key=lambda x: x[1])
        end_indexs = list(item[1] for item in pairs)
        dp = [1] * len(pairs)
        for i in range(1, len(dp)):
            if pairs[i][0] > pairs[i - 1][1]:
                dp[i] = dp[i - 1] + 1
            else:
                insert_index = bisect.bisect_left(end_indexs, pairs[i][0])
                if insert_index - 1 >= 0:
                    dp[i] = max(dp[i - 1], dp[insert_index - 1] + 1)
                else:
                    dp[i] = dp[i - 1]
        return dp[-1]

Greedy

class Solution:
    def findLongestChain(self, pairs: List[List[int]]) -> int:
        pairs.sort(key=lambda x:x[1])
        res = 0
        cur_end = pairs[0][0] - 1
        for i in range(len(pairs)):
            if pairs[i][0] > cur_end:
                res += 1
                cur_end = pairs[i][1]
        return res

你可能感兴趣的:(OJ题目记录,leetcode,算法,职场和发展)