Skip to main content
LeetCode 363, Hard. Topics: Array, Binary Search, Matrix, Prefix Sum, Ordered Set. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:

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

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, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026