Max Sum of Rectangle No Larger Than K — LeetCode 363 Python Solution
- Problem
- #363
- Pattern
- Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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
- 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).
Python solution
class Solution:
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
m, n = len(matrix), len(matrix[0])
ans = -inf
for i in range(m):
nums = [0] * n
for j in range(i, m):
for h in range(n):
nums[h] += matrix[j][h]
s = 0
ts = SortedSet([0])
for x in nums:
s += x
p = ts.bisect_left(s - k)
if p != len(ts):
ans = max(ans, s - ts[p])
ts.add(s)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m^2 \times n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 363. Max Sum of Rectangle No Larger Than K is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 363. Max Sum of Rectangle No Larger Than K?
- LeetCode 363. Max Sum of Rectangle No Larger Than K is rated Hard on LeetCode.
- What is the time complexity of LeetCode 363. Max Sum of Rectangle No Larger Than K?
- The Python solution on this page runs in O(m^2 \times n \times \log n).
- What is the space complexity of LeetCode 363. Max Sum of Rectangle No Larger Than K?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 363. Max Sum of Rectangle No Larger Than K cover?
- LeetCode 363. Max Sum of Rectangle No Larger Than K is tagged Array, Binary Search, Matrix, Ordered Set and Prefix Sum on LeetCode.