I have an integer matrix of size 4n x 4n. I need to select a part of the matrix of size n^2 from which adds up to the most.

For example if n = 3. I have a matrix of size 12 x 12. In the below picture, you can clearly see that n^2 square (outlined in red) adds up to the most. For simplicities sake, I made all the numbers 5, expect for 9 of the boxes which are 9999 so its clear that that is the n^2 squares that add up to the most.

enter image description here

My approach to solving this problem was to essentially create a n^2 square and brute force the entire 4n x 4n matrix. However, that runs in O(n^4) time complexity. How can I do it in O(n^2)?


1 Answer 1


Try building a summed area table—a table where the value in each cell is the sum of all the values above and to the left, inclusive, of the cell in the original table. See if you can figure out an $O(n^2)$ solution from that.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.