1749: Maximum-Absolute-Sum-of-Any-Subarray
Medium
Since we are trying to find the maximum
absolute sum of any subarray, and the sum of any
subarray can be calculated from the difference between 2
prefix sums, we can literally just iterate
through nums
, find the largest
prefix sum, largest
, and the
smallest prefix sum,
smallest
, and return
larget-smallest
.
Code:
class Solution {
public:
int maxAbsoluteSum(vector<int>& nums) {
int largest = 0;
int smallest = 0;
int prefix_sum = 0;
for (int i = 0; i < nums.size(); ++i) {
+= nums[i];
prefix_sum = max(largest, prefix_sum);
largest = min(smallest, prefix_sum);
smallest }
return largest-smallest;
}
};