gpt4 book ai didi

algorithm - 动态规划 : Find the rectangle in a grid that has the largest sum

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:16:13 25 4
gpt4 key购买 nike

我遇到了以下动态规划问题。

您有一个整数网格(因此包括负数)。找出数字总和最大的矩形。

知道如何对整个矩阵执行此操作吗?

我为单个数组解决了这个问题,所以我几乎遵循了最长递增子序列所做的,但仅限于连续的数字。

def array_largest_block(sequence)
len = sequence.size
parents = [nil]*len
my_largest = sequence
largest = sequence.max

for index in (1...len)
if my_largest[index] < my_largest[index] + my_largest[index - 1]
my_largest[index] = my_largest[index] + my_largest[index - 1]
parents[index] = index - 1
largest = [largest, my_largest[index]].max
end
end

end_index_of_largest_block = my_largest.find_index(largest)
i = end_index_of_largest_block
res = []
res << sequence[i]
while !parents[i].nil?
i = parents[i]
res << sequence[i]
end
return {l_sum: largest, start: i, end: end_index_of_largest_block}
end

所以我的想法是,

  1. 求出矩阵中每个方格的和(仅 1x1 个方格)
  2. 保存最大值以获得可能的答案
  3. 从可能的最小矩形开始运行相同的东西并计算所有矩形,直到找到最大值。这是数据库部分。

有什么想法吗?或者,如果你们不知道确切的解决方案,我应该看哪种 DP 类型的算法?

最佳答案

这可以在 O(N^3) 中完成,其中 N 是矩阵的大小。

您基本上选择矩形的左右列,然后以线性时间扫描各行(使用预先计算的总和)。

int totalBestSum = -10000000;
for (int leftCol = 1; leftCol <= N; leftCol++)
for (int rightCol = leftCol; rightCol <= N; rightCol++)
{
int curSum = 0, curBestSum = -10000000;
for (int row = 1; row <= N; row++) {
int rowSum = sumBetween(leftCol, rightCol, row);
curSum += rowSum;
if (curSum > curBestSum) curBestSum = curSum;
if (curSum < 0) curSum = 0;
}

if (curBestSum > totalBestSum) totalBestSum = curBestSum;
}

sumBetween 是一个返回两列之间特定行上数字总和的函数。它可以在恒定时间内使用预先计算的总和来实现。

int sumBetween(int leftCol, int rightCol, int row)
{
return sum[row][rightCol] - sum[row][leftCol - 1];
}

计算数组:

for (int row = 1; row <= N; row++)
for (int col = 1; col <= N; col++)
sum[row][col] = sum[row][col - 1] + matrix[row][col];

关于algorithm - 动态规划 : Find the rectangle in a grid that has the largest sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12786196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com