


Return 0, if there are no such two students present.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain a single integer ‘N’ which denotes the number of students in the row.
The second line of each test case contains the ‘N’ space-separated integers in which the “i-th” number represents the marks of the “i-th” student.
For each test case, print the maximum difference between the two students described above. If, there are no such students then print 0.
Output for every test case will be printed in a separate line.
You don’t need to print anything; It has already been taken care of.
1 <= T <= 50
2 <= N <= 10000
0 <= arr[ i ] <= 10^5
Where ‘T’ is the number of test cases.
Where 'N' is the number of students in the row and “arr[ i ]” denotes the marks of “i-th” student.
Time limit: 1 sec
The basic idea is to iterate through all the pairs of students and find the maximum difference between two students such that the first one has marks less than or equal to the second one.
The basic idea of this approach is to sort the given arrays according to the marks of the students in decreasing order. Now, if we traverse this new array from last to start then there is always arr[ i ] >= arr[ i + 1] and so, all we have to do is to find the maximum difference between the indexes of these students.
The basic idea of this approach is to store the minimum and maximum element in the left and right of each element and for this, we will use the concept of prefix and suffix arrays.
arr = [ 11, 4, 1, 5, 6, 7, 9, 8 ]
prefix = [ 11, 4, 1, 1, 1, 1, 1, 1 ]
suffix = [ 9, 9, 9, 9, 9, 9, 9, 8 ]
Here, “arr” is the given array, “prefix” is an array that holds the minimum value at every index while moving from left to right in the “arr”, and “suffix” is an array that holds the maximum value at every index while moving from right to left in the “arr”.
We start from ‘i’ = 0 and ‘j’ = 0 where ‘i’ is the iterator on prefix and ‘j’ is on the suffix. We increment ‘i’ by 1 because 11 is not less than or equal to 9. Now, ‘i’ becomes 1 and ‘j’ is still at 0. After this, we will keep incrementing the ‘j’ until the value corresponding to ‘j’ becomes less than or equal to the value corresponding to ‘i’ or ‘j’ reaches the end.
In the above example, ‘j’ will reach the end because the value corresponds to ‘i’ is 4 which is less than 8.
All we are trying to do is to always maintain property arr[ i ] <= arr[ j ] and find the maximum possible difference between the indexes.