Leetcode 646. Maximum Length of Pair Chain

Problem

Given a string s, find the longest palindromic subsequence's length in s.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Algorithm

Dynamic Programming (DP). Sort the data with a and b, define the state f(i) is the longest palindromic subsequence's length, then
f ( i ) = m a x { f ( j ) + 1 } , i f s o r t e d _ p a i r s i 0 > s o r t e d _ p a i r s j 1 f(i) = max\{ f(j) + 1 \}, \quad if \quad sorted\_pairsi0 > sorted\_pairsj1 f(i)=max{f(j)+1},ifsorted_pairsi0>sorted_pairsj1

Code

python3 复制代码
class Solution:
    def findLongestChain(self, pairs: List[List[int]]) -> int:
        plen = len(pairs)
        dp = [1] * plen
        sorted_pairs = sorted(pairs, key=lambda x: (x[0], x[1]))
        for i in range(1, plen):
            for j in range(i):
                if sorted_pairs[i][0] > sorted_pairs[j][1] and dp[i] <= dp[j]:
                     dp[i] = dp[j] + 1
        
        return max(dp)
相关推荐
Tisfy7 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6177 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
灯澜忆梦8 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
Shaoshing9 小时前
LeetCode100 155.最小栈
java·数据结构·算法
秋天的怀念_David9 小时前
算法一千零一夜 · 第四十夜 · 错层的状态码
java·程序人生·算法
纪念 2299 小时前
C++ 算法模板与错题 (差分)
开发语言·c++·算法
echoliuy10 小时前
二叉树—二叉搜索树 前序 中序 后序
算法·深度优先
怕浪猫10 小时前
机器人是当下薪酬最高却几乎没人学的技能:一份 6 个月从 0 到上手的学习路线
算法·架构·github
MobotStone10 小时前
打造高性价比 AI 应用:选对模型、用好缓存、持续测试
人工智能·算法