Max sum submatrix
Submissions: 915   Accuracy:

32.06%

  Difficulty: Easy   Marks: 2

Given a matrix, your aim is to find the maximum sum among all axb sub matrices of the matrix. The rows and columns of the submatrix must be contiguous. For example:

1 2 3 9

4 5 6 2

8 3 2 6

Let us solve for a = 3 and b = 2.

The first 3x2 submatrix is:

1 2

4 5

8 3

The sum of elements in this is 23.

The second 3x2 submatrix is:

2 3

5 6

3 2

The sum of elements in this is 21.

The third 3x2 submatrix is:

3 9

6 2

2 6

The sum of elements in this is 28.

The maximum among these is 28.
 

Input:
The first line contains the number of test cases. The first line of each test case contains two space separated integers N and M which denote the number of rows and columns in the matrix. The second line contains the values of the input matrix row wise. There are a total of N*M space separated positive integers in this line. The first M integers denote the first row of the matrix, the second M integers denote the second row and so on. The third line contains the number of queries Q for this test case. In the fourth line are 2*Q space separated positive integers which denote the queries. The first two number denote (a,b) for the first query. The third and the fourth number denote the second query and so on.

 

Output:
Corresponding to each test case, print the answers in a line in the same order as the queries. Answers to consecutive queries must be separated by space. Answer to a new test case must be in a new line.

 

Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
1 ≤ M ≤ 100
1 ≤ Q ≤ 30
1 ≤ a ≤ N ≤ 100
1 ≤ b ≤ M ≤ 100
1 ≤ Values in the matrix ≤ 1000

Example:
Input
1
3 4
1 2 3 9 4 5 6 2 8 3 2 6
3
1 1 2 2 3 3

Output
9 20 38

 

** For More Input/Output Examples Use 'Expected Output' option **

Author: Hemang Sarkar


If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.


to report an issue on this page.