[LeetCode] Maximum Absolute Sum of Any Subarray

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, then abs(x) = -x.
  • If x is a non-negative integer, then abs(x) = x.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int maxAbsoluteSum(vector<int>& nums) {
int mi = 0, ma = 0, sum = 0, res = 0;

for(auto& n : nums) {
sum += n;
res = max({res, abs(sum - mi), abs(sum - ma)});
mi = min(mi, sum);
ma = max(ma, sum);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/10/PS/LeetCode/maximum-absolute-sum-of-any-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.