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) {
prefix_sum += nums[i];
largest = max(largest, prefix_sum);
smallest = min(smallest, prefix_sum);
}
return largest-smallest;
}
};
complexity
- Time:
O(n)- Space:
O(1)