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
row total matrix:
column sums matrix:
That is, for the matrix of the form
row total matrix:
column sums matrix:
Another read that you can use the sum matrix of submatrices of the form
which for the reduced matrix looks like this
This matrix can be used to find the sum of the submatrix, for example, to find the value of an element
matrices
as
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 becomesO(n**4)in time andO(n**2)in memory. Is that enough for your question? - jfs