You are given an integer array nums
. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr]
is abs(numsl + numsl+1 + ... + numsr-1 + numsr)
.
Return the maximum absolute sum of any (possibly empty) subarray of nums
.
Note that abs(x)
is defined as follows:
- If
x
is a negative integer, thenabs(x) = -x
. - If
x
is a non-negative integer, thenabs(x) = x
.
Example 1:
Input: nums = [1,-3,2,3,-4] Output: 5 Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.
Example 2:
Input: nums = [2,-5,1,-4,3,-2] Output: 8 Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
任意子数组和的绝对值的最大值。
给你一个整数数组 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 。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-absolute-sum-of-any-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是贪心。这里找的是一段子数组,这一段子数组的和要不然非常大要不然非常小,这样才能使得其绝对值是最大的。但是由于子数组的长度是不确定的所以用一般的前缀和的思路应该是会超时的(O(n^2)的复杂度)。这道题算是个脑筋急转弯吧,思路有点类似前缀和,但是在统计前缀和的时候我们记录一个前缀和里面全局的最大值和最小值。那么最大值和最小值的差值这一段组成的子数组的和就一定是满足题意的最大值。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int maxAbsoluteSum(int[] nums) { 3 int max = 0; 4 int min = 0; 5 int sum = 0; 6 for (int num : nums) { 7 sum += num; 8 max = Math.max(max, sum); 9 min = Math.min(min, sum); 10 } 11 return max - min; 12 } 13 }