파비의 매일매일 공부기록

2023.08.26 Today's Challenge 본문

Problem Solving/LeetCode

2023.08.26 Today's Challenge

fabichoi 2023. 8. 26. 23:45

https://leetcode.com/problems/maximum-length-of-pair-chain/

 

Maximum Length of Pair Chain - LeetCode

Can you solve this real interview question? Maximum Length of Pair Chain - 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 i

leetcode.com

메모이제이션으로 푸는 문제

class Solution:
    def longestPairChain(self, i: int, pairs: List[List[int]], n: int, memo: List[int]) -> int:
        if memo[i] != 0:
            return memo[i]
        memo[i] = 1
        for j in range(i+1, n):
            if pairs[i][1] < pairs[j][0]:
                memo[i] = max(memo[i], 1+self.longestPairChain(j, pairs, n, memo))
        return memo[i]

    def findLongestChain(self, pairs: List[List[int]]) -> int:
        n = len(pairs)
        pairs.sort()
        memo = [0] * n
        ans = 0

        for i in range(n):
            ans = max(ans, self.longestPairChain(i, pairs, n, memo))
        return ans
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.08.28 Today's Challenge  (0) 2023.08.28
2023.08.27 Today's Challenge  (0) 2023.08.27
2023.08.25 Today's Challenge  (0) 2023.08.25
2023.08.24 Today's Challenge  (0) 2023.08.24
2023.08.23 Today's Challenge  (0) 2023.08.23
Comments