A subarray is a contiguous part of an array.
Your task is to find the maximum possible beauty of non-overlapping non-empty subarray pairs present in the array ‘A’.
Beauty of a subarray pair is defined as the absolute difference of the sum of elements of both the subarrays.
A subarray pair is said to be non-overlapping if there is no index common to both subarrays.
Example:Input: [1,2,-3,4,5]
Output: 12
In the given array we can consider the subarray pair { [-3] , [4,5] } which has the maximum beauty.
The first line will contain the integer 'T', denoting the number of test cases.
The first line of each test case contains one integer ‘N’ denoting the size of array ‘A’.
The second line of each test case contains ‘N’ single space-separated integers, elements of the array ‘A’.
Output format :
For each test case, Return the maximum possible beauty of all valid subarray pairs.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 10000
-10^9 <= A[i] <= 10^9
Time Limit: 1 sec
2
5
-6 3 1 -5 9
4
-3 1 9 -10
16
20
For the first case:
We can consider the subarray pair { [-6,3,1,-5] , [9] } which has the maximum beauty (9-(-6+3+1-5) = 16).
For the second case:
We can consider the subarray pair { [1,9] , [-10] } which has the maximum beauty ((1+9)-(-10) = 20).
2
8
6 1 -50 1 50 30 6 -100
6
55 19 -21 13 -10 -67
187
159
Check all possible subarray pairs.
In this approach, we will check all possible pairs of subarrays for finding maximum beauty. We can take four nested for loops. First, two loops will fix the first subarray and the last two will fix the other. In this way, we can find the beauty of all possible pairs and return the maximum beauty.
The steps are as follows:-
function getMaxBeauty(int N, [int]A):
O( N⁴ ), Where ‘N’ is the size of the given array ‘A’.
We are using four nested for loops for traversing over all possible subarray pairs.
Hence the time complexity is O( N⁴ ).
O( 1 ).
We are using constant extra space for string sums and the maximum beauty of subarray pairs.
Hence space complexity is O( 1 ).