[LeetCode] 1749. Maximum Absolute Sum of Any Subarray
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 }
二刷我再提供另一种思路,有点像53题找和最大的子数组的感觉。遍历 input 数组,用两个变量 max 和 min 分别记录遍历到的和最大,和最小的子数组的和分别是多少。
- 对于 min,如果当前 min >= 0 且又遇到一个正整数,那么对于找最小值是无益的,就丢弃前面累加起来的结果,直接 min = num
- 对于 max,如果当前 max <= 0 且又遇到一个负整数,那么对于找最大值是无益的,就丢弃前面累加起来的结果,直接 max = num
- 在找 min 和 max 的过程中同时更新 res,看到底谁的绝对值更大
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int maxAbsoluteSum(int[] nums) { 3 int res = 0; 4 int max = 0; 5 int min = 0; 6 for (int num : nums) { 7 if (min >= 0) { 8 min = num; 9 } else { 10 min += num; 11 } 12 13 if (max <= 0) { 14 max = num; 15 } else { 16 max += num; 17 } 18 19 res = Math.max(res, Math.abs(min)); 20 res = Math.max(res, Math.abs(max)); 21 } 22 return res; 23 } 24 }