

In this example, to maximise the value of ‘MAT[a][b]’ - ‘MAT[c][d]’ fulfilling the given conditions on indices (‘a’ > ‘c’ and ‘b’ > ‘d’), we take ‘a’ = 2, ‘b’ = 2, ‘c’ = 0 and ‘d’ = 0 . So, ‘MAT[a][b]’ = 9 and ‘MAT[c][d]’ = 1 and the value of ‘MAT[a][b]’ - ‘MAT[c][d]’ => 9 - 1 = 8 which is maximum among all possible combinations.
The first line of input contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains one integer ‘N’ representing the number of rows (or columns) of the square matrix ‘MAT’.
The next ‘N’ lines of each test case contain ‘N’ single space-separated integers denoting the values of ‘MAT’.
For each test case, print the maximum value of ‘MAT[a][b]’ - ‘MAT[c][d]’ over all possible choices of indices i.e. 0 <= ‘a’, ‘b’, ‘c’, ‘d’ < ‘N’ such that ‘a’ > ‘c’ and ‘b’ > ‘d’.
Print the output of each test case in a separate line.
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 100
2 <= ‘N’ <= 100
-10^5 <= ‘MAT[i][j]’ <= 10^5
Time Limit : 1 second
First of all we simply iterate the 2-D array ‘MAT’ and find a cell ‘MAT[c][d]’ where 0 <= ‘c’, ‘d’ < ‘N’ - ‘1’. Then we find the other cell ‘MAT[a][b]’ such that the given condition is fulfilled i.e. ‘a’ > ‘c’ and ‘b’ > ‘d’.
Here is the algorithm :
The idea is to pre-process the given matrix ‘MAT’ and store the minimum element encountered so far in a new 2-D array. We take an extra 2-D matrix ‘dp’ of size ‘N’ x ‘N’ and store the minimum element encountered from ‘MAT[0][0]’ to ‘MAT[i][j]’ at ‘dp[i][j]’. Then the maximum value of the function ‘maxVal’ is max(‘maxVal’, ‘MAT[i][j]’ - ‘dp[i - 1][j - 1]’).
Here is the algorithm :