# 363. Max Sum of Rectangle No Larger Than K

**<font color=red>难度: Hard</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/

> 内容描述

```
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.

Example:

Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2 
Explanation: Because the sum of rectangle [[0, 1], [-2, 3]] is 2,
             and 2 is the max number no larger than k (k = 2).
Note:

The rectangle inside the matrix must have an area > 0.
What if the number of rows is much larger than the number of columns?
```

## 解题方案

> 思路 1
******- 时间复杂度: O(row * col^2)******- 空间复杂度: O(row)******

参考[Youtube视频](https://www.youtube.com/watch?time_continue=812&v=yCQN096CwWM)

将第53题的kadane's Algorithm运用到二维矩阵上来


因为后面会用到bisect_left，所以提前要将sys.maxsize放到sums里面去，避免后面sums[bisect.bisect_left(sums, cur_sum - k)]会产生list out of range的错误

beats 45.59%

```python
class Solution:
    def maxSumSubmatrix(self, matrix, k):
        """
        :type matrix: List[List[int]]
        :type k: int
        :rtype: int
        """
        row = len(matrix)
        col = len(matrix[0]) if row else 0
        res = -sys.maxsize
        
        for l in range(col):
            dp = [0] * row
            for r in range(l, col):
                for i in range(row):
                    dp[i] += matrix[i][r]
                # Find the max subarray no more than K 
                sums, cur_sum, cur_max = [sys.maxsize], 0, -sys.maxsize 
                for sm in dp:
                    bisect.insort(sums, cur_sum)
                    cur_sum += sm
                    cur_max = max(cur_max, cur_sum - sums[bisect.bisect_left(sums, cur_sum - k)])
                res = max(res, cur_max)
        return res
```

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

那就将矩阵转置一下再用上面的方法就行了

