LeetCode 题解工作台
绝对值表达式的最大值
给你两个长度相等的整数数组,返回下面表达式的最大值: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| 其中下标 i , j 满足 0 。 示例 1: 输入: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] 输出: 13 …
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们不妨令 $x_i = arr1[i]$, $y_i = arr2[i]$,由于 和 的大小关系不影响表达式的值,我们不妨假设 $i \ge j$,那么表达式可以变为: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你两个长度相等的整数数组,返回下面表达式的最大值:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
其中下标 i,j 满足 0 <= i, j < arr1.length。
示例 1:
输入:arr1 = [1,2,3,4], arr2 = [-1,4,5,6] 输出:13
示例 2:
输入:arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4] 输出:20
提示:
2 <= arr1.length == arr2.length <= 40000-10^6 <= arr1[i], arr2[i] <= 10^6
解题思路
方法一:数学 + 枚举
我们不妨令 , ,由于 和 的大小关系不影响表达式的值,我们不妨假设 ,那么表达式可以变为:
因此,我们只要求出 的最大值 ,以及最小值 ,其中 。那么答案就是所有 中的最大值。
时间复杂度 ,其中 是数组长度。空间复杂度 。
相似题目:
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
dirs = (1, -1, -1, 1, 1)
ans = -inf
for a, b in pairwise(dirs):
mx, mi = -inf, inf
for i, (x, y) in enumerate(zip(arr1, arr2)):
mx = max(mx, a * x + b * y + i)
mi = min(mi, a * x + b * y + i)
ans = max(ans, mx - mi)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each array element is processed once per sign pattern. Space complexity is O(1) extra space beyond input arrays, as only running maxima and minima are stored. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for recognition that naive nested loops will exceed time limits on large arrays.
- question_mark
Expect candidates to convert absolute values into a fixed set of sign combinations.
- question_mark
Watch for the candidate correctly maintaining running maxima and minima per transformed pattern.
常见陷阱
外企场景- error
Attempting brute-force O(n^2) iteration, which fails for array lengths up to 40000.
- error
Forgetting to include the index difference |i-j| in the transformed expressions.
- error
Miscalculating sign combinations, leading to incorrect maximum values.
进阶变体
外企场景- arrow_right_alt
Compute the minimum of |arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| instead of the maximum.
- arrow_right_alt
Extend to three or more arrays, adjusting the four-pattern approach to eight or more combinations.
- arrow_right_alt
Handle dynamic updates to arrays, requiring efficient recalculation of maxima and minima.