![]() |
VOOZH | about |
Given a matrix mat[][] of size N x M and an array queries[] of size Q, containing (a, b) pairs. The task is to find the maximum sum among all (a x b) sub-matrices of the matrix mat[][].
Note: The rows and columns of the sub-matrix must be contiguous.
Examples:
Input: N = 3, M = 4, Q = 1, queries[] = {(3, 2)}
mat[][] = {{1, 2, 3, 9},
{4, 5, 6, 2},
{8, 3, 2, 6}}
Output: 28
Explanation:
Here 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 are 28.Input: N = 3, M = 4, Q = 3, queries[] = {(1, 1), (2, 2), (3, 3)}
mat[][] = {{1, 2, 3, 9},
{4, 5, 6, 2},
{8, 3, 2, 6}}
Output: 9 20 38
Naive Approach: The simplest approach to solve this problem is for each query, find sum of every sub-matrix and print the largest one.
Time Complexity: O(Q*(N*M)^2), where Q is the number of queries, N and M are the number of rows and columns of the matrix mat[][].
Auxiliary Space: O(1)
Efficient Approach: This problem can be solved by doing some pre-processing before answering all the queries. Follow the steps below to solve this problem:
Reference: https://www.geeksforgeeks.org/dsa/submatrix-sum-queries/
Below is the implementation of the above approach:
9 20 38
Time Complexity: O(Q*N*M), where Q is the number of queries, N and M are the number of rows and columns of the matrix mat[][].
Auxiliary Space: O(N*M)