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 firstname.lastname@example.org. 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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find Maximum Length Of A Square Submatrix Having Sum Of Elements At-Most K
- Submatrix of given size with maximum 1's
- Largest possible square submatrix with maximum AND value
- Check if a matrix contains a square submatrix with 0 as boundary element
- Maximum size of square such that all submatrices of that size have sum less than K
- Maximum sum of any submatrix of a Matrix which is sorted row-wise and column-wise
- Minimum sum submatrix in a given 2D array
- Count of submatrix with sum X in a given Matrix
- Maximum value in a matrix which contain intersecting concentric submatrix
- Smallest submatrix with Kth maximum XOR
- Submatrix Sum Queries
- Smallest submatrix required to be removed such that sum of the remaining matrix is divisible by K
- Bitwise XOR of a submatrix of a matrix generated from a given array
- Maximum size square Sub-Matrix with sum less than or equals to K
- Summed Area Table - Submatrix Summation
- Maximize the binary matrix by filpping submatrix once
- XOR of a submatrix queries
- Check if matrix A can be converted to B by changing parity of corner elements of any submatrix
- Minimum cells to be flipped to get a 2*2 submatrix with equal elements
- Given an n x n square matrix, find sum of all sub-squares of size k x k