LeetCode 题解工作台
任意子数组和的绝对值的最大值
给你一个整数数组 nums 。一个子数组 [nums l , nums l+1 , ..., nums r-1 , nums r ] 的 和的绝对值 为 abs(nums l + nums l+1 + ... + nums r-1 + nums r ) 。 请你找出 nums 中 和的绝对值 最大的…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示以 结尾的子数组的和的最大值,定义 表示以 结尾的子数组的和的最小值。那么 和 的状态转移方程如下: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数数组 nums 。一个子数组 [numsl, numsl+1, ..., numsr-1, numsr] 的 和的绝对值 为 abs(numsl + numsl+1 + ... + numsr-1 + numsr) 。
请你找出 nums 中 和的绝对值 最大的任意子数组(可能为空),并返回该 最大值 。
abs(x) 定义如下:
- 如果
x是负整数,那么abs(x) = -x。 - 如果
x是非负整数,那么abs(x) = x。
示例 1:
输入:nums = [1,-3,2,3,-4] 输出:5 解释:子数组 [2,3] 和的绝对值最大,为 abs(2+3) = abs(5) = 5 。
示例 2:
输入:nums = [2,-5,1,-4,3,-2] 输出:8 解释:子数组 [-5,1,-4] 和的绝对值最大,为 abs(-5+1-4) = abs(-8) = 8 。
提示:
1 <= nums.length <= 105-104 <= nums[i] <= 104
解题思路
方法一:动态规划
我们定义 表示以 结尾的子数组的和的最大值,定义 表示以 结尾的子数组的和的最小值。那么 和 的状态转移方程如下:
最后答案为 的最大值。
由于 和 只与 和 有关,因此我们可以使用两个变量代替数组,将空间复杂度降低到 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
f = g = 0
ans = 0
for x in nums:
f = max(f, 0) + x
g = min(g, 0) + x
ans = max(ans, f, abs(g))
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Can the candidate efficiently optimize space usage with dynamic programming?
- question_mark
How well does the candidate handle state transitions in dynamic programming problems?
- question_mark
Does the candidate understand how to compute absolute sums within subarrays efficiently?
常见陷阱
外企场景- error
Forgetting to consider the possibility of empty subarrays, which can affect the result when calculating the maximum absolute sum.
- error
Not handling negative numbers correctly in the subarray sums and absolute value calculations.
- error
Overcomplicating the problem by using unnecessary data structures, when a solution with constant space can be achieved.
进阶变体
外企场景- arrow_right_alt
What if we asked for the maximum sum, rather than the absolute sum? This would eliminate the need to consider the negative sum possibilities.
- arrow_right_alt
How would the solution change if the array contained only positive numbers or only negative numbers?
- arrow_right_alt
What if we asked for the subarray with the smallest absolute sum instead?