> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Max Sum of Rectangle No Larger Than K

> Tested Python solution for LeetCode 363 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 363, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Binary Search](/catalog/topics/binary-search), [Matrix](/catalog/topics/matrix), [Prefix Sum](/catalog/topics/prefix-sum), [Ordered Set](/catalog/topics/ordered-set). [View on LeetCode](https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 363   # by problem number
lcpy gen -s max_sum_of_rectangle_no_larger_than_k   # by problem name
```

## Problem

Given an \<code>m x n\</code> matrix \<code>matrix\</code> and an integer \<code>k\</code>, return \<em>the max sum of a rectangle in the matrix such that its sum is no larger than\</em> \<code>k\</code>.

It is \<strong>guaranteed\</strong> that there will be a rectangle with a sum no larger than \<code>k\</code>.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg)

```
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).
```

```
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
* -10^5 \<= k \<= 10^5

**Follow up:** What if the number of rows is much larger than the number of columns?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/max_sum_of_rectangle_no_larger_than_k/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/max_sum_of_rectangle_no_larger_than_k/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from bisect import bisect_left, insort


class Solution:
    # Time: O(m^2 * n * log n)
    # Space: O(n)
    def max_sum_submatrix(self, matrix: list[list[int]], k: int) -> int:
        rows, cols = len(matrix), len(matrix[0])
        best = -(10**9)
        for top in range(rows):
            col_sums = [0] * cols
            for bottom in range(top, rows):
                row = matrix[bottom]
                for c in range(cols):
                    col_sums[c] += row[c]
                sorted_sums = [0]
                running = 0
                for s in col_sums:
                    running += s
                    i = bisect_left(sorted_sums, running - k)
                    if i < len(sorted_sums):
                        best = max(best, running - sorted_sums[i])
                    insort(sorted_sums, running)
        return best
```

## Complexity

| Time | Space |
| - | - |
| O(m^2 \* n \* log n) | O(n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.