Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Program to find maximum absolute sum of any subarray in Python



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
Updated on: 2021-10-06T08:12:13+05:30

433 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements