【问题标题】:Dynamic Programming: Find the rectangle in a grid that has the largest sum动态规划:在网格中找到总和最大的矩形
【发布时间】:2012-09-28 23:13:27
【问题描述】:

我遇到了以下动态编程问题。

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

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

我为单个数组解决了它,所以我几乎遵循了最长递增子序列所做的事情,但仅适用于连续数字。

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 类型算法?

【问题讨论】:

    标签: algorithm dynamic-programming maximize


    【解决方案1】:

    这可以在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];
    }
    

    计算sum 数组:

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

    【讨论】:

      【解决方案2】:

      似乎是重复的,但请看这里:Getting the submatrix with maximum sum?

      可以在O(N^3)做。

      你到底为什么要使用“NP-complete”标签?:D

      【讨论】:

      • 嘿,我认为动态编程问题是 Np 完整的,就像背包...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      • 2015-04-29
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      相关资源
      最近更新 更多