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 nums1[i] and nums2[j] such that:

  • nums1[i] == nums2[j], 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]
相关推荐
緈福的街口8 分钟前
【leetcode】3. 无重复字符的最长子串
算法·leetcode·职场和发展
麦仓分享34 分钟前
C++算法动态规划3
算法·动态规划
HEX9CF1 小时前
【Linux】awk 命令详解及使用示例:结构化文本数据处理工具
linux·chrome·算法
Cl_rown去掉l变成C1 小时前
第J3-1周:DenseNet算法 实现乳腺癌识别
人工智能·pytorch·算法
努力学习的小廉1 小时前
我爱学算法之—— 前缀和(中)
开发语言·redis·算法
保持学习ing1 小时前
黑马Java面试笔记之 集合篇(算法复杂度+ArrayList+LinkedList)
java·笔记·算法·面试
LunaGeeking1 小时前
三分算法与DeepSeek辅助证明是单峰函数
c语言·c++·算法·编程·信奥赛·ai辅助学习·三分
Darkwanderor2 小时前
数论——同余问题全家桶3 __int128和同余方程组
c++·算法·数论·中国剩余定理
Xyz_Overlord2 小时前
机器学习——聚类算法
算法·机器学习·聚类
dessler2 小时前
代理服务器-LVS的3种模式与调度算法
运维·服务器·网络·算法·nginx·tomcat·lvs