LeetCode 题解工作台
最高乘法得分
给你一个大小为 4 的整数数组 a 和一个大小 至少 为 4 的整数数组 b 。 你需要从数组 b 中选择四个下标 i 0 , i 1 , i 2 , 和 i 3 ,并满足 i 0 1 2 3 。你的得分将是 a[0] * b[i 0 ] + a[1] * b[i 1 ] + a[2] * b[i …
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们设计一个函数 $\textit{dfs}(i, j)$,表示从数组 的第 个元素开始,从数组 的第 个元素开始,能够获得的最大得分。那么答案就是 $\textit{dfs}(0, 0)$。 函数 $\textit{dfs}(i, j)$ 的计算方式如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个大小为 4 的整数数组 a 和一个大小 至少为 4 的整数数组 b。
你需要从数组 b 中选择四个下标 i0, i1, i2, 和 i3,并满足 i0 < i1 < i2 < i3。你的得分将是 a[0] * b[i0] + a[1] * b[i1] + a[2] * b[i2] + a[3] * b[i3] 的值。
返回你能够获得的 最大 得分。
示例 1:
输入: a = [3,2,5,6], b = [2,-6,4,-5,-3,2,-7]
输出: 26
解释:
选择下标 0, 1, 2 和 5。得分为 3 * 2 + 2 * (-6) + 5 * 4 + 6 * 2 = 26。
示例 2:
输入: a = [-1,4,5,-2], b = [-5,-1,-3,-2,-4]
输出: -1
解释:
选择下标 0, 1, 3 和 4。得分为 (-1) * (-5) + 4 * (-1) + 5 * (-2) + (-2) * (-4) = -1。
提示:
a.length == 44 <= b.length <= 105-105 <= a[i], b[i] <= 105
解题思路
方法一:记忆化搜索
我们设计一个函数 ,表示从数组 的第 个元素开始,从数组 的第 个元素开始,能够获得的最大得分。那么答案就是 。
函数 的计算方式如下:
- 如果 ,表示数组 已经遍历完了,此时如果数组 也遍历完了,返回 ,否则返回负无穷;
- 如果 ,表示数组 已经遍历完了,返回 ;
- 否则,我们可以不选择数组 的第 个元素,直接跳到下一个元素,即 ;也可以选择数组 的第 个元素,此时得分为 ,再加上 。我们取这两者的最大值作为 的返回值。
我们可以使用记忆化搜索的方式,避免重复计算。
时间复杂度 ,空间复杂度 。其中 和 分别为数组 和 的长度。
class Solution:
def maxScore(self, a: List[int], b: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if j >= len(b):
return 0 if i >= len(a) else -inf
if i >= len(a):
return 0
return max(dfs(i, j + 1), a[i] * b[j] + dfs(i + 1, j + 1))
return dfs(0, 0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate recognizes the importance of dynamic programming for state transitions.
- question_mark
Candidate correctly identifies the need for greedy selection in conjunction with dynamic programming.
- question_mark
Candidate efficiently manages the large input sizes with optimizations to reduce complexity.
常见陷阱
外企场景- error
Overcomplicating the approach with unnecessary loops.
- error
Failing to efficiently transition states in the DP table.
- error
Misunderstanding the problem by not considering array b’s ordered indices.
进阶变体
外企场景- arrow_right_alt
Consider variations in the size of array b, which might require different optimization strategies.
- arrow_right_alt
Test the solution with varying values in array a and how it influences score maximization.
- arrow_right_alt
Alter the problem to handle multiple sets of arrays for more complex scoring scenarios.