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’.
For each test case, Return the maximum possible beauty of all valid subarray pairs.
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
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.
In this approach, we’ll precompute the maximum and minimum subarray sums in a 2D array. Take two 2D arrays, one for storing the minimum and maximum subarray sums in the prefix fashion and the other in suffix fashion.
We will be using kadane’s algorithm to get the maximum and minimum subarray sums. After storing the minimum and maximum sums iterate through the indexes of the array and check for the maximum beauty pair.
The possible maximum beauties at any index can be the difference between the maximum subarray sum of prefix part and minimum subarray sum of suffix part or the difference between the minimum subarray sum of prefix part and maximum subarray sum of suffix part.
Prefix[i][0]- It stores the maximum subarray sum from index 0 tol index i.
Prefix[i][1]- It stores the minimum subarray sum from index 0 to index i.
Suffix[i][0]- It stores the maximum subarray sum from index i to index N-1.
Suffix[i][1]- It stores the minimum subarray sum from index i to index N-1.