LeetCode 题解工作台

任意子数组和的绝对值的最大值

给你一个整数数组 nums 。一个子数组 [nums l , nums l+1 , ..., nums r-1 , nums r ] 的 和的绝对值 为 abs(nums l + nums l+1 + ... + nums r-1 + nums r ) 。 请你找出 nums 中 和的绝对值 最大的…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示以 结尾的子数组的和的最大值,定义 表示以 结尾的子数组的和的最小值。那么 和 的状态转移方程如下: $$

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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
lightbulb

解题思路

方法一:动态规划

我们定义 f[i]f[i] 表示以 nums[i]nums[i] 结尾的子数组的和的最大值,定义 g[i]g[i] 表示以 nums[i]nums[i] 结尾的子数组的和的最小值。那么 f[i]f[i]g[i]g[i] 的状态转移方程如下:

f[i]=max(f[i1],0)+nums[i]g[i]=min(g[i1],0)+nums[i]\begin{aligned} f[i] &= \max(f[i - 1], 0) + nums[i] \\ g[i] &= \min(g[i - 1], 0) + nums[i] \end{aligned}

最后答案为 max(f[i],g[i])max(f[i], |g[i]|) 的最大值。

由于 f[i]f[i]g[i]g[i] 只与 f[i1]f[i - 1]g[i1]g[i - 1] 有关,因此我们可以使用两个变量代替数组,将空间复杂度降低到 O(1)O(1)

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。其中 nn 为数组 numsnums 的长度。

1
2
3
4
5
6
7
8
9
10
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
speed

复杂度分析

指标
时间O(N)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

任意子数组和的绝对值的最大值题解:状态·转移·动态规划 | LeetCode #1749 中等