跳转至

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

问题描述#

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

解题思路#

求子数组的最大和与最小和。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def maxAbsoluteSum(self, nums: List[int]) -> int:
        ans = nums[0]
        pos = neg = 0

        for x in nums:
            pos += x
            neg += x
            if pos < 0: pos = 0
            if neg > 0: neg = 0
            ans = max(ans, pos, -neg)

        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    int maxAbsoluteSum(vector<int>& nums) {
        int ans = nums[0];
        int pos = 0, neg = 0;

        for (auto x : nums) {
            pos += x, neg += x;
            if (pos < 0) pos = 0;
            if (neg > 0) neg = 0;
            ans = max({ans, pos, -neg});
        }

        return ans;
    }
};
返回顶部

在手机上阅读