这里的算法应该是O(k<sup>2</sup>*h)(它可能被优化为O(k*h*w))并且对空间要求很轻O(k)。它的原理是,任何具有最高非零和的子矩阵必须在其左边缘有一个点(否则,在这个子矩阵的右侧可能有一个总和更高的子矩阵) .因此,为了找到最大的和,我们遍历每个非零点并找到在其左边缘具有该点的所有子矩阵,将 W 内的所有非零点求和到当前点的右侧子矩阵中的每一行。
下面是该算法的 python 实现。它首先创建每行中的点的字典,然后按所述迭代每个点,将非零点的总和存储在该行的右侧,然后基于该点计算每个子矩阵的总和。如果总和大于当前最大值,则存储该值及其位置。请注意,这使用 0 索引列表,因此对于您的示例数据,最大值为 (2, 3)。
from collections import defaultdict
def max_subarray(n, nzp, h, w):
maxsum = 0
maxloc = (0, 0)
# create a dictionary of points in a row
nzpd = defaultdict(list)
for p in nzp:
nzpd[p[0]].append(p[1])
# iterate over each of the non-zero points, looking at all
# submatrixes that have the point on the left side
for p in nzp:
y, x = p
pointsright = [0] * n
for r in range(max(y-(h-1), 0), min(y+h, n)):
# points within w to the right of this column on this row
pointsright[r] = len([p for p in nzpd[r] if x <= p <= x+(w-1)])
# compute the sums for each of the possible submatrixes
for i in range(-h+1, h):
thissum = sum(pointsright[max(y+i, 0):min(y+i+h, n)])
if thissum > maxsum:
maxsum = thissum
maxloc = (y, x)
# adjust the position in case the submatrix would extend beyond the last row/column
maxloc = (min(n-h, maxloc[0]), min(n-w, maxloc[1]))
# print the max sum
print(f'{maxsum} found at location {maxloc}')
示例用法:
nzp = [(0, 6), (1, 9), (2, 3), (2, 4), (2, 5),
(3, 1), (3, 4), (3, 6), (4, 3), (4, 3),
(4, 10), (5, 5), (6, 4), (6, 8), (7, 5),
(8, 3), (10, 2), (10, 8), (11, 4), (11, 10)
]
max_subarray(12, nzp, 2, 4)
输出:
5 found at location (2, 3)
Demo on rextester