


You are given an M X N matrix of integers ARR. Your task is to find the maximum sum rectangle.
Maximum sum rectangle is a rectangle with the maximum value for the sum of integers present within its boundary, considering all the rectangles that can be formed from the elements of that matrix.
A rectangle is a 2-D polygon with opposite sides parallel and equal to each other.
For example:Consider following matrix:
1 2 -1 -4 -20
-8 -3 4 2 1
3 8 10 1 3
-4 -1 1 7 -6
The rectangle (1,1) to (3,3) is the rectangle with the maximum sum, i.e. 29.
1 2 -1 -4 -20
-8 |-3 4 2 | 1
3 | 8 10 1 | 3
-4 |-1 1 7 | -6
The first line of input contains an integer 'T' representing the number of the test case. Then the test case follows.
The first line of each test case contains two space-separated integers M and N representing the size of the matrix ARR.
Each of the next M lines contains N space-separated integers representing the elements of the matrix ARR.
Output Format :
For each test case, return the value of the sum for the maximum sum rectangle.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= M, N <= 100
-10^5 <= ARR[i] <=10^5
Time Limit : 1 sec
3
1 1
1
1 2
-1 1
2 2
1 -1
2 2
1
1
4
(i) Maximum sum rectangle is (0,0)-(0,0)
(ii) Maximum sum rectangle is (0,1)-(0,1)
(iii) Maximum sum rectangle is (1,0)-(1,1)
3
1 2
0 0
2 2
1 0
0 1
4 5
1 2 -1 -4 -20
-8 -3 4 2 1
3 8 10 1 3
-4 -1 1 7 -6
0
2
29
(i) Maximum sum rectangle is (0,0)-(0,1)
(ii) Maximum sum rectangle is (0,0)-(1,1)
(iii) Maximum sum rectangle is (1,1)-(3,3)
Try to identify every rectangle in the array and calculate the sum for each one of them.
In this approach, we'll try to consider each rectangle that can be formed using elements of the array. To do this we fix (X1,Y1) coordinates of starting vertex and iterate through the matrix for every pair (X2,Y2) as the coordinates of ending vertex. Now we have a rectangle with coordinates (X1,Y1), (X1,Y2), (X2,Y1) and (X2,Y2).
We'll find the sum of elements within this rectangle and compare it with MAXSUM. if it is greater than MAXSUM, we'll update the value of MAXSUM.
O(N^3*M^3), where M and N are the numbers of rows and columns, respectively.
The time complexity of the algorithm will be O(N^3*M^3) because we’ll be using six nested loops to calculate the sum for each rectangle.
O(1).
The space complexity of the algorithm is O(1) because we are not using any additional space.