![]() |
VOOZH | about |
Given a matrix mat[][] of dimensions N * M, and an integer K, the task is to find the maximum sum of any rectangle possible from the given matrix, whose sum of elements is at most K.
Examples:
Input: mat[][] ={{1, 0, 1}, {0, -2, 3}}, K = 2
Output: 2
Explanation: The maximum sum possible in any rectangle from the matrix is 2 (<= K), obtained from the matrix {{0, 1}, {-2, 3}}.Input: mat[][] = {{2, 2, -1}}, K = 3
Output: 3
Explanation: The maximum sum rectangle is {{2, 2, -1}} is 3 ( <- K).
Naive Approach: The simplest approach is to check for all possible submatrices from the given matrix whether the sum of its elements is at most K or not. If found to be true, store the sum of that submatrix. Finally, print the maximum sum of such submatrices obtained.
Time Complexity: O(N6)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by using an approach similar to finding the maximum sum rectangle in a 2D matrix. The only difference is that the sum of the rectangle must not exceed K. The idea is to fix the left and right columns one by one and in each iteration, store the sum of each row in the current rectangle and find the maximum subarray sum less than K in this array. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
2
Time Complexity: O(N3*log(N))
Auxiliary Space: O(N)