Suppose we have an array called nums. We have to find the absolute sum of a subarray [nums_l, nums_l+1, ..., nums_r-1, nums_r] is |nums_l + nums_l+1 + ... + nums_r-1 + nums_r|. We have to find the maximum absolute sum of any subarray of nums (that subarray can possibly be empty).
So, if the input is like nums = [2,-4,-3,2,-6], then the output will be 11 because the subarray [2,-4,-3,2] has maximum absolute subarray sum |2 + (-4) + (-3) + 2| = 11.
To solve this, we will follow these steps −
n:= size of nums
ans:= 0, temp:= 0
for i in range 0 to n - 1, do
if temp < 0, then
temp:= 0
temp:= temp + nums[i]
ans:= maximum of ans and |temp|
temp:= 0
for i in range 0 to n - 1, do
if temp > 0, then
temp:= 0
temp:= temp + nums[i]
ans:= maximum of ans and |temp|
return ans
Example
Let us see the following implementation to get better understanding −
def solve(nums): n=len(nums) ans=0 temp=0 for i in range(n): if (temp<0): temp=0 temp=temp+nums[i] ans=max(ans,abs(temp)) temp=0 for i in range(n): if (temp>0): temp=0 temp=temp+nums[i] ans=max(ans,abs(temp)) return ans nums = [2,-4,-3,2,-6] print(solve(nums))
Input
[2,-4,-3,2,-6]
Output
11