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]
相关推荐
ZC跨境爬虫20 分钟前
LeetCode 13. 罗马数字转整数(多解法详解 + Java Python 实现)
java·python·leetcode
.道阻且长.25 分钟前
10.LeetCode算法习题讲解--滑动窗口--最大连续为一的个数
算法·leetcode·职场和发展
学习中.........1 小时前
Karpathy nanoGPT 教程到底讲了什么
人工智能·算法·语言模型
城管不管1 小时前
重生——第十次面试之开源中国一面挂
java·linux·开发语言·算法·面试·职场和发展·开源
地平线开发者2 小时前
征程6|YOLOv5x 在 Horizon 征程6 上的端到端部署实践(下)
算法·自动驾驶
speop3 小时前
llm-algo-leetcode |Task01
算法·leetcode·职场和发展
艾为电子3 小时前
【应用方案】电视沉浸式音频升级: 电视音频 awinic“芯片 + 算法” 一体化解决方案
算法·音视频
大熊背3 小时前
树莓派相机自动白平衡详解(二)
算法·白平衡·isppipeline
Scabbards_3 小时前
面试Leetcode - 算法合集
算法·leetcode·面试
chuan.bai3 小时前
Java RAG 实战附录:qwen3 与 bge-m3 模型切换指南
java·人工智能·算法