Program to find sum of rectangle whose sum at most k in Python


Suppose we have a 2d matrix and another value k, we have to find the largest sum of a rectangle where sum ≤ k.

So, if the input is like

5−2
710

and k = 15, then the output will be 12, as we can take the rectangle [5, 7] to get sum of 12 less than 15.

To solve this, we will follow these steps −

  • n := row count of a

  • m := column count of a

  • ans := inf

  • for i1 in range 0 to n, do

    • row := a list of size m and fill with 0

    • for i2 in range i1 to n, do

      • for j in range 0 to m, do

        • row[j] := row[j] + a[i2, j]

      • s := a new set

      • insert 0 into s

      • sum := 0

      • for j in range 0 to m, do

        • sum := sum + row[j];

        • temp := a list for all items in s which is larger than (sum − k)

        • if size of temp > 0, then

          • u := minimum of temp

          • ans := maximum of ans and (sum − u)

        • insert sum into s

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, a, k):
      n = len(a)
      if n == 0:
         return 0;
      m = len(a[0])
      ans = -999999;
      for i1 in range(n):
         row = [0]*m;
         for i2 in range(i1, n):
            for j in range(m):
               row[j] += a[i2][j]
            s = set()
            s.add(0)
            sum = 0
            for j in range(m):
               sum += row[j];
               temp = [e for e in s if e > (sum − k)]
            if len(temp) > 0:
               u = min(temp)
               ans = max(ans, sum − u)
            s.add(sum)
         return ans
ob = Solution()
matrix = [
   [5, −2],
   [7, 10]
]
k = 15
print(ob.solve(matrix, k))

Input

[
[5, −2],
[7, 10]
], 15

Output

12

Updated on: 26-Dec-2020

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements