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

Given a 2D matrix and a value k, we need to find the largest sum of a rectangle whose sum is at most k. This problem combines matrix manipulation with optimization techniques.

Problem Understanding

Consider this matrix with k = 15:

5 -2
7 10

We can form rectangles like [5, 7] with sum = 12, [5, -2, 7, 10] with sum = 20, etc. The largest sum ? 15 is 12.

Algorithm Steps

  • For each pair of rows (i1, i2), compress the matrix vertically

  • Convert the 2D problem into a 1D subarray problem

  • Use a set to track prefix sums for efficient lookup

  • Find the maximum valid rectangle sum

Implementation

class Solution:
    def solve(self, matrix, k):
        n = len(matrix)
        if n == 0:
            return 0
        m = len(matrix[0])
        max_sum = float('-inf')
        
        # Try all pairs of rows
        for i1 in range(n):
            row = [0] * m
            for i2 in range(i1, n):
                # Compress rows i1 to i2 into a single row
                for j in range(m):
                    row[j] += matrix[i2][j]
                
                # Find max subarray sum <= k in this compressed row
                prefix_sums = {0}
                current_sum = 0
                
                for j in range(m):
                    current_sum += row[j]
                    
                    # Find the smallest prefix sum > (current_sum - k)
                    valid_prefixes = [p for p in prefix_sums if p >= (current_sum - k)]
                    
                    if valid_prefixes:
                        min_prefix = min(valid_prefixes)
                        max_sum = max(max_sum, current_sum - min_prefix)
                    
                    prefix_sums.add(current_sum)
        
        return max_sum

# Test the solution
solution = Solution()
matrix = [
    [5, -2],
    [7, 10]
]
k = 15
result = solution.solve(matrix, k)
print(f"Maximum rectangle sum ? {k}: {result}")
Maximum rectangle sum ? 15: 12

How It Works

The algorithm uses row compression technique:

  1. Row compression: For rows i1 to i2, sum all elements column-wise

  2. 1D conversion: The 2D rectangle problem becomes finding max subarray sum ? k

  3. Prefix sum optimization: Use a set to store prefix sums for O(log n) lookup

Example Walkthrough

# Let's trace through the algorithm step by step
matrix = [[5, -2], [7, 10]]
k = 15

print("Step-by-step execution:")
print("Matrix:", matrix)
print("k =", k)
print()

# Row 0 only: [5, -2]
print("Row 0 only: [5, -2]")
print("Subarray sums: 5, 3, -2")
print("Valid sums ? 15: 5, 3, -2 ? max = 5")
print()

# Rows 0-1: [5+7, -2+10] = [12, 8] 
print("Rows 0-1 combined: [12, 8]")
print("Subarray sums: 12, 20, 8")
print("Valid sums ? 15: 12, 8 ? max = 12")
print()

# Row 1 only: [7, 10]
print("Row 1 only: [7, 10]")
print("Subarray sums: 7, 17, 10") 
print("Valid sums ? 15: 7, 10 ? max = 10")
print()

print("Overall maximum: 12")
Step-by-step execution:
Matrix: [[5, -2], [7, 10]]
k = 15

Row 0 only: [5, -2]
Subarray sums: 5, 3, -2
Valid sums ? 15: 5, 3, -2 ? max = 5

Rows 0-1 combined: [12, 8]
Subarray sums: 12, 20, 8
Valid sums ? 15: 12, 8 ? max = 12

Row 1 only: [7, 10]
Subarray sums: 7, 17, 10
Valid sums ? 15: 7, 10 ? max = 10

Overall maximum: 12

Time Complexity

The time complexity is O(n² × m²) where n is rows and m is columns. The space complexity is O(m) for storing prefix sums.

Conclusion

This algorithm efficiently finds the maximum rectangle sum by using row compression and prefix sum optimization. The key insight is converting the 2D problem into multiple 1D subarray problems.

Updated on: 2026-03-25T14:02:53+05:30

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements