Could you advise the algorithm that solves the following problem?

Given a rectangular matrix of size nxm and the number k. We need to find a submatrix (the original matrix is ​​also considered a submatrix) of the largest area (the number of columns multiplied by the number of rows), whose sum of elements is less than or equal to k. Return the area of ​​this matrix. All elements of the matrix and the number k are positive integers. The algorithm must have complexity below O (n ^ 6). You can use additional structures based on the matrix.

At the moment, I realized that the matrix of sums of columns and rows can help: a matrix of sums of tables for a matrix with elements of the form

equation

row total matrix:

equation

column sums matrix:

equation

That is, for the matrix of the form

equation

row total matrix:

equation

column sums matrix:

equation

Another read that you can use the sum matrix of submatrices of the form

equation

which for the reduced matrix looks like this

equation

This matrix can be used to find the sum of the submatrix, for example, to find the value of an element

equation

matrices

equation

as equation

  • What has already happened? Add to the question. - 0xdb
  • The complexity is O (n ^ 6), and n is what? If M x N, then the direct search is obtained as O (n ^ 3), if n is N, then the direct search is obtained only as your O (n ^ 6), only it is more logical to set n as M x N, therefore it is not clear a little bit ... - user239133
  • by n I mean one of the dimensions of the matrix, the naive algorithm has complexity O (n ^ 6) - Mark Sobolev
  • @MarcoSobolev, if this is nevertheless exactly one of the sizes, then the second one can only be fixed. Then the complexity is again O (n ^ 3). Optimization comes to my mind only too complicated, so that I can immediately write some code. If the enumeration of all subsets can be implemented while preserving the complexity O (n ^ 2) so that the subsets of the same size P x ​​Q are sequentially iterated, then the sum can be considered as a fast two-dimensional moving average method. Its complexity is still O (n), but at least the one-dimensional version lends itself to some optimization . - user239133
  • Assuming that the number of elements in the matrix is O(n**2) . The most naive approach enumerates all possible child matrices (i, j, nrows, ncolumns) - O(n**4) and naively calculates the sum from the very beginning n * m - O(n**2) -> O(n**6) algorithm. If you use the S [i, j] matrix, then you can calculate the sum for O (1): Sum(i,j,nrows,ncolumns) = S[i+nrows,j+ncolumns] - S[i+nrows,j] - S[i,j+ncolumns] +S[i,j] that is, using S [i, j], the naive algorithm becomes O(n**4) in time and O(n**2) in memory. Is that enough for your question? - jfs

0