LeetCode 题解工作台
两个子序列的最大点积
给你两个数组 nums1 和 nums2 。 请你返回 nums1 和 nums2 中两个长度相同的 非空 子序列的最大点积。 数组的非空子序列是通过删除原数组中某些元素(可能一个也不删除)后剩余数字组成的序列,但不能改变数字间相对顺序。比方说, [2,3,5] 是 [1,2,3,4,5] 的一个子…
2
题型
6
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义 表示 的前 个元素和 的前 个元素构成的两个子序列的最大点积。初始时 $f[i][j] = -\infty$。 对于 ,我们有以下几种情况:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你两个数组 nums1 和 nums2 。
请你返回 nums1 和 nums2 中两个长度相同的 非空 子序列的最大点积。
数组的非空子序列是通过删除原数组中某些元素(可能一个也不删除)后剩余数字组成的序列,但不能改变数字间相对顺序。比方说,[2,3,5] 是 [1,2,3,4,5] 的一个子序列而 [1,5,3] 不是。
示例 1:
输入:nums1 = [2,1,-2,5], nums2 = [3,0,-6] 输出:18 解释:从 nums1 中得到子序列 [2,-2] ,从 nums2 中得到子序列 [3,-6] 。 它们的点积为 (2*3 + (-2)*(-6)) = 18 。
示例 2:
输入:nums1 = [3,-2], nums2 = [2,-6,7] 输出:21 解释:从 nums1 中得到子序列 [3] ,从 nums2 中得到子序列 [7] 。 它们的点积为 (3*7) = 21 。
示例 3:
输入:nums1 = [-1,-1], nums2 = [1,1] 输出:-1 解释:从 nums1 中得到子序列 [-1] ,从 nums2 中得到子序列 [1] 。 它们的点积为 -1 。
提示:
1 <= nums1.length, nums2.length <= 500-1000 <= nums1[i], nums2[i] <= 1000
点积:
定义a = [a1, a2,…, an]和b= [b1, b2,…, bn]的点积为:这里的 Σ 指示总和符号。
解题思路
方法一:动态规划
我们定义 表示 的前 个元素和 的前 个元素构成的两个子序列的最大点积。初始时 。
对于 ,我们有以下几种情况:
- 不选 或者不选 ,即 ;
- 选 和 ,即 。
最终答案即为 。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 和 的长度。
class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
f = [[-inf] * (n + 1) for _ in range(m + 1)]
for i, x in enumerate(nums1, 1):
for j, y in enumerate(nums2, 1):
v = x * y
f[i][j] = max(f[i - 1][j], f[i][j - 1], max(0, f[i - 1][j - 1]) + v)
return f[m][n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They ask how your DP prevents choosing empty subsequences when every product is negative.
- question_mark
They push on why the transition must compare taking the current pair alone versus extending dp[i+1][j+1].
- question_mark
They ask whether the same recurrence still works when zeros appear and when one strong pair beats every longer subsequence.
常见陷阱
外企场景- error
Initializing DP with 0 and accidentally allowing an empty subsequence to beat valid negative answers.
- error
Using a longest-common-subsequence style transition without the take-current-pair-alone case, which misses single-pair optima.
- error
Forgetting that skipping is allowed independently in either array, so the DP must compare skip nums1 and skip nums2 at every state.
进阶变体
外企场景- arrow_right_alt
Return the actual subsequences that produce the maximum dot product instead of only the score.
- arrow_right_alt
Restrict the solution to subsequences of exactly k matched pairs, which adds a length dimension to the DP.
- arrow_right_alt
Change the objective to minimum dot product, which flips the transition logic and changes which negative states are desirable.
这里的 Σ 指示总和符号。