leetcode.363. Max Sum of Rectangle No Larger Than K

来源:互联网 发布:单片机sram是什么 编辑:程序博客网 时间:2024/05/16 12:29

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:

Given matrix = [  [1,  0, 1],  [0, -2, 3]]k = 2

The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 and 2 is the max number no larger than k (k = 2).

Note:

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

思路: 一种naive的算法就是枚举每个矩形块, 时间复杂度为O((mn)^2), 可以做少许优化时间复杂度可以降低到O(mnnlogm), 其中m为行数, n为列数. 

先求出任意两列之间的所有数的和, 然后再枚举任意两行之间的和, 而我们优化的地方就在后者. 我们用s[x]来表示第x行从a列到b列的和. 遍历一遍从第0行到最后一行的求和数组, 并依次将其放到二叉搜索树中, 这样当我们知道了从第0行到当前行的和的值之后, 我们就可以用lower_bound在O(log n)的时间复杂度内找到能够使得从之前某行到当前行的矩阵值最接近k. 也就是说求在之前的求和数组中找到第一个位置使得大于(curSum - k), 这种做法的原理是在curSum之下规定了一个bottom-line, 在这上面的第一个和就是(curSum-val)差值与k最接近的数. 还需要注意的是预先为二叉搜索树加一个0值, 这种做法的原理是如果当前curSum小于k!

class Solution {public:    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {        int row = matrix.size();          if(!row) return 0;          int col = matrix[0].size();          if(!col) return 0;          int ret = INT_MIN;                    for(int i=0; i<col; ++i) {              vector<int> sum(row, 0);              for(int j=i; j<col; ++j) {                  for(int r=0; r<row; ++r) sum[r] += matrix[r][j];                  int curSum = 0, curMax = INT_MIN;                  set<int> sumSet;                  sumSet.insert(0);                  for(int r=0; r<row; ++r) {                      curSum += sum[r];                      auto it = sumSet.lower_bound(curSum-k);                      if(it != sumSet.end()) curMax = max(curMax, curSum-*it);                      sumSet.insert(curSum);                  }                  ret = max(ret, curMax);              }          }                    return ret;      }};


0 0
原创粉丝点击