Leetcode 1035. Uncrossed Lines

Problem

You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.

We may draw connecting lines: a straight line connecting two numbers nums1i and nums2j such that:

  • nums1i == nums2j, and
  • the line we draw does not intersect any other connecting (non-horizontal) line.

Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).

Return the maximum number of connecting lines we can draw in this way.

Algorithm

Dynamic Programming (DP): same as Longest Common Subsequence (LCS).

  • If s1[i] != s2[j]:
    F ( i , j ) = max ⁡ ( F ( i − 1 , j ) , F ( i , j − 1 ) ) F(i, j) = \max\left( F(i-1, j), F(i, j-1) \right) F(i,j)=max(F(i−1,j),F(i,j−1))

  • If s1[i] == s2[j]:
    F ( i , j ) = F ( i − 1 , j − 1 ) + 1 F(i, j) = F(i-1, j-1) + 1 F(i,j)=F(i−1,j−1)+1

Code

python3 复制代码
class Solution:
    def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
        l1, l2 = len(nums1) + 1, len(nums2) + 1
        dp = [[0] * l2 for _ in range(l1)] 

        for i in range(1, l1):
            for j in range(1, l2):
                if nums1[i-1] == nums2[j-1]:
                    dp[i][j] = dp[i-1][j-1] + 1
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        
        return dp[l1-1][l2-1]
相关推荐
拳里剑气1 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
ysa0510302 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill1232 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
wabs6663 小时前
关于图论【卡码网110.字符串迁移的思考】
数据结构·算法·图论
hanlin033 小时前
刷题笔记:力扣第242、349题(哈希表)
笔记·算法·leetcode
only-qi5 小时前
大模型Agent面试攻略:落地工程痛点、评估体系与Agentic RAG核心精讲
人工智能·算法·面试·职场和发展·langchain·rag
Gauss松鼠会7 小时前
【GaussDB】GaussDB锁阻塞源头查询
java·开发语言·前端·数据库·算法·gaussdb·经验总结
oier_Asad.Chen7 小时前
【洛谷题解/AcWing题解】洛谷P4011 孤岛营救问题/AcWing1131拯救大兵瑞恩
数据结构·笔记·学习·算法·动态规划·图论·宽度优先
逻辑君7 小时前
基于 A2C 算法的双足机器人行走控制
人工智能·深度学习·算法·机器学习·机器人
冻柠檬飞冰走茶7 小时前
PTA基础编程题目集 7-19 支票面额(C语言实现)
c语言·开发语言·数据结构·算法