
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Program to find maximum ascending subarray sum using Python
- Program to find maximum sum obtained of any permutation in Python
- Program to find the maximum sum of the subarray modulo by m in Python
- Maximum sum of absolute difference of any permutation in C++
- Program to find out the sum of the maximum subarray after a operation in Python
- Program to find maximum product of contiguous subarray in Python
- Program to find maximum subarray min-product in Python
- Program to find maximum score of a good subarray in Python
- Program to find minimum absolute sum difference in Python
- Program to find maximum length of subarray with positive product in Python
- Program to find maximum adjacent absolute value sum after single reversal in C++
- C++ Program to Find the maximum subarray sum using Binary Search approach
- Using Kadane’s algorithm to find maximum sum of subarray in JavaScript
- Program to find range sum of sorted subarray sums using Python
- Find Maximum Sum Strictly Increasing Subarray in C++
