
Consider arr =[1, 2, 3, 4, 5], we can take indices i = 0, and j = 4, so difference is 4 - 0 = 4, and arr[4] > arr[0]. Hence the answer is 4.
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains a single integer ‘N’ denoting the size of the array ‘arr’.
The second line of each test case contains ‘N’ space-separated integers representing the elements of the array ‘arr’.
For each test case, print a single integer representing the maximum difference between ‘j’ and ‘i’ such that arr[j] > arr[i].
The output of each test case will be printed in a separate line.
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10 ^ 6
1<= arr[i] <= 10 ^ 9
Time limit: 1 sec
We will run two for loops to check whether there exist two indices, such that the difference of indexes is maximized and arr[j] > arr[i].
Algorithm:
We will sort the array and maintain the order of indexes. After sorting the array ‘arr’, we know that the elements are in increasing order. So all we need to do is maximize the difference between the indexes. For every index, we need to check for the highest index present ahead. We can do this in constant time if we maintain a suffix array that provides us the information of the maximum index.
Algorithm:
All we need to do is maintain two pointers left and right, such that arr[right] > arr[left] and right-left are maximum.
Now, if we try to fix the left pointer for any element ‘E’, we will check if there is an element less in value behind this element ‘E’. If yes, then we will fix the left pointer there. Similarly, if we try to fix the right pointer for any element ‘E’, we will check if there exists an element higher in value in front of this element ‘E’. If yes, then we will fix the right pointer there.
In order to check for the higher element in front, we can maintain a maximum DP-suffix array which can get us the maximum element in constant time. Also, in order to check for the lesser element from the left, we can maintain a minimum DP-prefix array.
Algorithm: