Given an array, find the maximum absolute difference between the sum of elements of two non-overlapping subarrays in linear time.

Please note that the problem specifically targets subarrays that are contiguous (i.e., occupy consecutive positions) and inherently maintains the order of elements.

 
For example,

Input:  A[] = { -3, -2, 6, -3, 5, -9, 3, 4, -1, -8, 2 }
 
Output: The maximum absolute difference is 19.
 
The two subarrays are { 6, -3, 5 }, { -9, 3, 4, -1, -8 } whose sum of elements are 8 and -11, respectively. So, abs(8-(-11)) or abs(-11-8) = 19.

Practice this problem

The idea is to calculate the maximum and minimum sum of subarrays ending and starting at any index i in the array. Then for each index i, consider the maximum absolute value of the following:

  • Maximum subarray sum in subarray ending at index i – Minimum subarray sum in subarray starting at index i+1
  • Minimum subarray sum in subarray ending at index i – Maximum subarray sum in subarray starting at index i+1

If Kadane’s algorithm is used, the time complexity of this solution is O(n2), where n is the size of the input.

 
We can solve this problem in O(n) by using extra space. The idea is to create four auxiliary arrays, left_min[i], left_max[], right_min[], right_min[], such that:

  • left_max[i] stores the maximum sum of subarray in A(0, i)
  • right_max[i] stores the maximum sum of subarray in A(i, n-1)
  • left_min[i] stores the minimum sum of subarray in A(0, i)
  • right_min[i] stores the minimum sum of subarray in A(i, n-1)

To fill left_max[] and right_max[] arrays in linear time, we can use the standard Kadane’s algorithm for finding the maximum sum of a subarray.

To fill left_min[] and right_min[] arrays, we can still use Kadane’s algorithm by transforming the array so that each element’s sign is reversed. Then find the maximum sum of subarray for each index and invert its sign to get the minimum subarray sum.

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum absolute difference is 19

Java


Download  Run Code

Output:

The maximum absolute difference is 19

Python


Download  Run Code

Output:

The maximum absolute difference is 19