Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Max Sum of Rectangle No Larger Than K

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "363" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k. It is guaranteed that there will be a rectangle with a sum no larger than k. Example 1: Input: matrix = [[1,0,1],[0,-2,3]], k = 2 Output: 2 Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2). Example 2: Input: matrix = [[2,2,-1]], k = 3 Output: 3 Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 100 -100 <= matrix[i][j] <= 100 -105 <= k <= 105 Follow up: What if the number of rows is much larger than the number of columns?

Explanation

Here's the solution:

  • Prefix Sum Optimization: Calculate prefix sums for each row to efficiently compute the sum of elements within any column range. This converts the problem to a 1D sub-array problem for each row.
  • Binary Search with Sorted Set: Use a sorted set (implemented using SortedList in Python) to maintain the cumulative sums encountered so far for a given column range. For each new cumulative sum, perform a binary search to find the smallest value in the set that, when subtracted, results in a value less than or equal to k. This efficiently finds the maximum sub-array sum no larger than k.
  • Iterate through Column Combinations: Iterate through all possible column combinations to explore all potential rectangles. For each column range, apply the prefix sum and binary search approach to find the maximum sum.

  • Time Complexity: O(min(m, n)^2 max(m, n) log(max(m, n))), Space Complexity: O(max(m, n))

Code

    from sortedcontainers import SortedList

def max_sub_matrix_sum(matrix, k):
    """
    Finds the max sum of a rectangle in the matrix such that its sum is no larger than k.

    Args:
        matrix: A list of lists representing the matrix.
        k: An integer representing the target sum.

    Returns:
        The max sum of a rectangle in the matrix such that its sum is no larger than k.
    """
    m = len(matrix)
    n = len(matrix[0])
    max_sum = float('-inf')

    for left in range(n):
        row_sums = [0] * m
        for right in range(left, n):
            for i in range(m):
                row_sums[i] += matrix[i][right]

            current_sum = 0
            seen = SortedList([0])
            for row_sum in row_sums:
                current_sum += row_sum

                # Find the smallest value in 'seen' such that current_sum - val <= k
                # or, val >= current_sum - k.  This is binary search for the
                # smallest value >= current_sum - k.

                idx = seen.bisect_left(current_sum - k)
                if idx < len(seen):
                    max_sum = max(max_sum, current_sum - seen[idx])

                seen.add(current_sum)

    return max_sum

More from this blog

C

Chatmagic blog

2894 posts