![]() |
VOOZH | about |
Given a 2d array mat[][] of order n * n, and an integer k. Your task is to find a submatrix of order k * k, such that sum of all the elements in the submatrix is maximum possible.
Note: Matrix mat[][] contains zero, positive and negative integers.
Examples:
👁 rectangleInput: k = 3
mat[][] = [ [ 1, 2, -1, 4 ]
[ -8, -3, 4, 2 ]
[ 3, 8, 10, -8 ]
[ -4, -1, 1, 7 ] ]
Output: 20
Explanation: The submatrix enclosed in blue boundary is the maximum sum submatrix of order 3 * 3.Input: k = 3
mat[][] = [ [ 1, 1, 1, 1, 1 ]
[ 2, 2, 2, 2, 2 ]
[ 3, 8, 6, 7, 3 ]
[ 4, 4, 4, 4, 4 ]
[ 5, 5, 5, 5, 5 ] ]
Output: 48
Explanation: The following submatrix of order k * k has sum 48, which is maximum possible:
[ [ 8, 6, 7 ]
[ 4, 4, 4 ]
[ 5, 5, 5 ] ]Input: k = 1
mat[][] = [ [ 4 ] ]
Output: 4
Explanation: The given matrix contains only a single element, thus the max possible sum is 4.
This problem is mainly an extension of Maximum Sum of a Subarray of Size k
The idea is to generate all possible submatrices of order k * k, and find sum of its elements. The maximum obtained sum is the answer.
We run two nested loops, where the outer loop runs from 0 to n - k, and marks the row, while the inner row runs from 0 to n - k and marks the current column. For each iteration of the inner loop, again run two nested loops, where the outer loop runs from i to i + k - 1, and inner loop runs from j to j + k - 1. For each iteration of innermost loop add the cell value to the sum. At last store the max of obtained sum and current answer.
20
The idea is to preprocess the given square matrix. In the pre-processing step, calculate sum of all vertical strips of size k x 1 in a temporary square matrix stripSum[][]. Once we have sum of all vertical strips, we can calculate sum of first sub-square in a row as sum of first k strips in that row, and for remaining sub-squares, we can calculate sum in constant time by removing the leftmost strip of previous sub-square and adding the rightmost strip of new square.
20
The idea is to use Dynamic Programming to precompute the sum of all the sub-matrices having their top-left cell [0, 0] (Like prefix sum in 1 D array), and then use it to find the sums of submatrices of order k * k and pick the maximum possible. To do so, create a 2d array dp[][] of order n * n, where dp[i][j] stores the sum of all the elements of sub-matrix mat[0...i][0...j].
Follow the below given steps:
20
Related Articles:
Given an n x n square matrix, find sum of all sub-squares of size k x k
Maximum sum rectangle in a 2D matrix