

You are given ‘ARR’ = [1, 2, 3, 1]. The difference between the nearest left and the right smaller element of ‘ARR[2],’ i.e., 2 - 1 = 1 is the maximum possible. Hence the answer is 1.
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains an integer, ‘N’, representing the size of the ‘ARR’.
The second line of each test case contains ‘N’ space-separated integers, representing the elements of ‘ARR’.
For each test case, print a single integer, denoting the maximum absolute difference between the nearest left and the right smaller element of every element in ‘ARR’.
The output of each test case will be printed in a separate line.
1 <= T <= 10
1 <= N <= 5000
1 <= ARR[i] <= 10^6
Time limit: 1 sec
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
In this approach, we will use two arrays, ‘LEFTSMALLER’ to store the nearest left smaller element for every element of ‘ARR’ and ‘the RIGHT SMALLER’ to store the nearest right smaller for every element in ‘ARR’. ‘LEFTSMALLER[I]’ will store the nearest left smaller element of the ith element of ‘ARR’. Similarly, ‘RIGHTSMALLER[I]’ will store the nearest right smaller element of the ith element of ‘ARR’.
Then, we update the maximum difference according to the difference of ‘LEFTSMALLER[I]’ and ‘RIGHTSMALLER[I]’.
To find the nearest right smaller element of any element, we will run a loop on its right side. As soon as we find an element on its right side that is smaller than it, we will break the loop, assign it as the nearest right smaller element of this element, move forward, and do the same for the next element.
Now, to find the nearest left smaller element of any element, we will reverse the ‘ARR’ and find the nearest right smaller element.
Algorithm:
Maintain a function ‘FINDRIGHTSMALLER’(‘N’, ‘ARR’, ‘RIGHTSMALLER’)
Maintain a function ‘REVERSE’(‘ARR’)
This approach is the same as the previous, one but instead of using two loops to find the smaller element, we will use a stack, which will help us to reduce time complexity from quadratic to linear.
For every element, we will find the nearest left smaller element using a stack. We will iterate through ‘ARR’, and for every element, we will keep removing the top of the stack while it is greater than or equal to the current element. Once all the greater elements have been removed, we will check if the stack still has elements or not. If the stack still has elements, they all will be smaller than the current, and the top of the stack will be the nearest smaller element.
Algorithm:
Maintain a function ‘FINDLEFTSMALLER’(‘N’, ‘ARR’, ‘LEFTSMALLER’)
Maintain a function ‘REVERSE’(‘ARR’)