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]
相关推荐
Physicist in Geophy.6 分钟前
一维波动方程(从变分法角度)
线性代数·算法·机器学习
im_AMBER12 分钟前
Leetcode 115 分割链表 | 随机链表的复制
数据结构·学习·算法·leetcode
Liue6123123113 分钟前
【YOLO11】基于C2CGA算法的金属零件涂胶缺陷检测与分类
人工智能·算法·分类
!!!!81318 分钟前
蓝桥备赛Day1
数据结构·算法
Mr_Xuhhh18 分钟前
介绍一下ref
开发语言·c++·算法
夏鹏今天学习了吗22 分钟前
【LeetCode热题100(99/100)】柱状图中最大的矩形
算法·leetcode·职场和发展
啊阿狸不会拉杆28 分钟前
《机器学习导论》第 9 章-决策树
人工智能·python·算法·决策树·机器学习·数据挖掘·剪枝
Mr_Xuhhh29 分钟前
C++11实现线程池
开发语言·c++·算法
若水不如远方31 分钟前
分布式一致性(三):共识的黎明——Quorum 机制与 Basic Paxos
分布式·后端·算法
only-qi38 分钟前
leetcode24两两交换链表中的节点 快慢指针实现
数据结构·算法·链表