VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-not-exceeding-k-possible-for-any-rectangle-of-a-matrix/

⇱ Maximum sum not exceeding K possible for any rectangle of a Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum not exceeding K possible for any rectangle of a Matrix

Last Updated : 23 Jul, 2025

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:

  • Initialize a variable, say res, that stores the maximum sum of elements of the submatrix having sum at most K.
  • Iterate over the range [0, M - 1] using the variable i for the left column and perform the following steps:
    • Initialize an array V[] of size N, to store the sum of elements of each row in between the left and right column pair.
    • Iterate over the range [0, M - 1] using a variable j for the right column and perform the following steps:
      • Find the sum between current left and right column of every row and update the sum in the array V[].
      • Find the maximum sum subarray with sum less than K in V[] and store the result in ans.
      • If the value of ans is greater than the value of res, update res to ans.
  • After completing the above steps, print the value of res as the result.

Below is the implementation of the above approach:


Output: 
2

 

Time Complexity: O(N3*log(N))
Auxiliary Space: O(N)

Comment