Given an N x N matrix, find a k x k submatrix where k <= N and k >= 1, such that sum of all the elements in submatrix is maximum. The input matrix can contain zero, positive and negative numbers.
We strongly recommend you to minimize your browser and try this yourself first.
A Simple Solution is to consider all possible sub-squares of size k x k in our input matrix and find the one which has maximum sum. Time complexity of above solution is O(N2k2).
We can solve this problem in O(N2) time. This problem is mainly an extension of this problem of printing all sums. The idea is to preprocess the given square matrix. In the preprocessing 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 O(1) time by removing the leftmost strip of previous subsquare and adding the rightmost strip of new square.
Below is the implementation of above idea.
Maximum sum 3 x 3 matrix is 8 6 7 4 4 4 5 5 5
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Maximum size square sub-matrix with all 1s
- Print a given matrix in spiral form
- Magic Square
- Find the row with maximum number of 1s
- Print unique rows in a given boolean matrix
- Inplace (Fixed space) M x N size matrix transpose | Updated
- Maximum sum rectangle in a 2D matrix | DP-27
- Print all possible paths from top left to bottom right of a mXn matrix
- Given an n x n square matrix, find sum of all sub-squares of size k x k
- Print all elements in sorted order from row and column wise sorted matrix
- Collect maximum points in a grid using two traversals
- Collect maximum coins before hitting a dead end
- Submatrix Sum Queries
- Maximum size rectangle binary sub-matrix with all 1s
- Print n x n spiral matrix using O(1) extra space
- Inplace rotate square matrix by 90 degrees | Set 1
- Find maximum length Snake sequence
- Print shortest path to print a string on screen
- Find size of the largest '+' formed by all ones in a binary matrix
- Print K'th element in spiral form of matrix