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]
相关推荐
满分观察网友z1 分钟前
从一团乱麻到井然有序:我的海量任务调度“秘密武器”( 1353. 最多可以参加的会议数目)
算法
m0_5350646039 分钟前
C++类模版与友元
java·c++·算法
满分观察网友z1 小时前
从“最短响应路径”到二叉树最小深度:一个Bug引发的BFS探险之旅(111. 二叉树的最小深度)
后端·算法
阿里云大数据AI技术1 小时前
Post-Training on PAI (4):模型微调SFT、DPO、GRPO
人工智能·算法·云计算
CoovallyAIHub1 小时前
卷积网络到底能不能“定位”?一次对空间表示能力的深度解析
深度学习·算法·计算机视觉
用户40315986396631 小时前
和谐程序组
java·算法
用户40315986396631 小时前
缓存优化模拟
java·算法
用户40315986396631 小时前
遥控小车
java·算法
羑悻的小杀马特2 小时前
从混沌到秩序:数据科学的热力学第二定律破局——线性回归的熵减模型 × 最小二乘的能量最小化 × 梯度下降的负反馈控制系统,用物理定律重构智能算法的统一场论
人工智能·算法·机器学习
仟濹2 小时前
【数据结构】「栈」(顺序栈、共享栈、链栈)
c语言·数据结构·算法