solution.md 2.3 KB
Newer Older
ToTensor's avatar
ToTensor 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
# 矩形区域不超过 K 的最大数值和

<p>给你一个 <code>m x n</code> 的矩阵 <code>matrix</code> 和一个整数 <code>k</code> ,找出并返回矩阵内部矩形区域的不超过 <code>k</code> 的最大数值和。</p>

<p>题目数据保证总会存在一个数值和不超过 <code>k</code> 的矩形区域。</p>

<p> </p>

<p><strong>示例 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg" style="width: 255px; height: 176px;" />
<pre>
<strong>输入:</strong>matrix = [[1,0,1],[0,-2,3]], k = 2
<strong>输出:</strong>2
<strong>解释:</strong>蓝色边框圈出来的矩形区域 <code>[[0, 1], [-2, 3]]</code> 的数值和是 2,且 2 是不超过 k 的最大数字(k = 2)。
</pre>

<p><strong>示例 2:</strong></p>

<pre>
<strong>输入:</strong>matrix = [[2,2,-1]], k = 3
<strong>输出:</strong>3
</pre>

<p> </p>

<p><strong>提示:</strong></p>

<ul>
	<li><code>m == matrix.length</code></li>
	<li><code>n == matrix[i].length</code></li>
	<li><code>1 <= m, n <= 100</code></li>
	<li><code>-100 <= matrix[i][j] <= 100</code></li>
	<li><code>-10<sup>5</sup> <= k <= 10<sup>5</sup></code></li>
</ul>

<p> </p>

<p><strong>进阶:</strong>如果行数远大于列数,该如何设计解决方案?</p>


## template

```python
ToTensor's avatar
ToTensor 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
import bisect

class Solution:
    def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
        m = len(matrix)
        Row, Col = len(matrix), len(matrix[0])
        res = float("-inf")
        for ru in range(Row):
            col_sum = [0 for _ in range(Col)]
            for rd in range(ru, Row):
                for c in range(Col):
                    if matrix[rd][c] == k:
                        return k
                    col_sum[c] += matrix[rd][c]

                presum = [0]
                cur_sum = 0
                for colsum in col_sum:
                    cur_sum += colsum
                    idx = bisect.bisect_left(presum, cur_sum - k)
                    if idx < len(presum):
                        res = max(res, cur_sum - presum[idx])
                        if res == k:
                            return k
                    bisect.insort(presum, cur_sum)

        return res
ToTensor's avatar
ToTensor 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
```

## 答案

```python

```

## 选项

### A

```python

```

### B

```python

```

### C

```python

```