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?

思路

  使用l和r划定长方形的左右边界范围,然后在这个范围内,依次记录长方形的上界固定为第一行,下界从第一行到最后一行对应的长方形的和到数组sum。现在问题转换为寻找最合适的sum[j]-sum[i](j和i对应长方形的上下界),使得该值不大于k,但是最接近k。这个问题可以从Quora上找到解答:

  You can do this in O(nlog(n))

  First thing to note is that sum of subarray (i,j] is just the sum of the first j elements less the sum of the first i elements. Store these cumulative sums in the array cum. Then the problem reduces to finding  i,j such that i<j and cum[j]−cum[i] is as close to k but lower than it.

  To solve this, scan from left to right. Put the cum[i] values that you have encountered till now into a set. When you are processing cum[j] what you need to retrieve from the set is the smallest number in the set such which is not smaller than cum[j]−k. This lookup can be done in O(log(n)) using lower_bound. Hence the overall complexity is O(nlog⁡(n)).

  Here is a c++ function that does the job, assuming that K>0 and that the empty interval with sum zero is a valid answer. The code can be tweaked easily to take care of more general cases and to return the interval itself.

  对应代码:

int best_cumulative_sum(int ar[],int N,int K)
{
set<int> cumset;
cumset.insert();
int best=,cum=;
for(int i=;i<N;i++)
{
cum+=ar[i];
set<int>::iterator sit=cumset.lower_bound(cum-K);
if(sit!=cumset.end())best=max(best,cum-*sit);
cumset.insert(cum);
}
return best;
}

  在上述基础之上,我们稍加改变,就能够写出下述代码完成此题了。

class Solution {
public:
int maxSumSubmatrix(vector<vector<int>> &matrix, int k) {
int row = matrix.size();
if (row == )
return ;
int col = matrix[].size();
int ret = INT_MIN;
for (int l = ; l < col; l++) {
vector<int> sums(row, );
for (int r = l; r < col; r++) {
for (int i = ; i < row; i++)
sums[i] += matrix[i][r];
// Find the max subarray no more than K
set<int> sumSet;
sumSet.insert();
int curSum = ;
int curMax = INT_MIN;
for (auto sum:sums) {
curSum += sum;
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;
}
};

Max Sum of Rectangle No Larger Than K的更多相关文章

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

    /* * 363. Max Sum of Rectangle No Larger Than K * 2016-7-15 by Mingyang */ public int maxSumSubmatri ...

  2. [LeetCode] Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  3. Leetcode: Max Sum of Rectangle No Larger Than K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  4. 【leetcode】363. Max Sum of Rectangle No Larger Than K

    题目描述: Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the ma ...

  5. [Swift]LeetCode363. 矩形区域不超过 K 的最大数值和 | Max Sum of Rectangle No Larger Than K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  6. 363 Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  7. [LeetCode] 363. Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  8. 【LeetCode】363. Max Sum of Rectangle No Larger Than K 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/max-sum- ...

  9. 第十三周 Leetcode 363. Max Sum of Rectangle No Larger Than K(HARD)

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

随机推荐

  1. CodeForces 546 D. Soldier and Number Game(素数有关)

    Description Two soldiers are playing a game. At the beginning first of them chooses a positive integ ...

  2. CodeForces 525D Arthur and Walls

    广搜.看了官方题解才会的..... 定义2*2的小矩阵,有三个是点,一个是星,这样的小矩阵被称为元素块. 首先把所有元素块压入队列,每次取出对头,检查是否还是元素块,如果是 那么将那个*改为点,否则跳 ...

  3. 通过ReconstructMe实现3D扫描

    实物3D建模 目前在3D游戏制作过程中,需要专业人士花几天甚至数星期的时间,借助于Autodesk 3ds Max和Maya等昂贵的软件工具制作3D模型.纹理和动画.游戏制作中经常使用一种方法,即设计 ...

  4. Chapter 1 First Sight——16

    I drove around the school, following the line of traffic. 我开车绕学校随着交通线. 我开车穿过校园,紧跟着大部队. I was glad to ...

  5. If only it could be all the same like we first me

    为什么 你当时对我好 Why? You nice to me at that time. 又为什么 现在变得冷淡了 Why? Now you give a cold shoulder to me. 我 ...

  6. DataBinding注意事项Error parsing XML: duplicate attribute以及如何在listview中使用DataBinding

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...

  7. JSP标准标签库(JSTL)--国际化标签库 fmt

    JSTL中使用fmt.tld作为格式化标签库的定义文件 No. 功能分类 标签名称 描述 1 国际化标签 <fmt:setLocale> 设置一个全局的地区代码 2 <fmt:req ...

  8. jquery获取页面相关尺寸

    $(windows).width();获取页面可视宽度 $(windows).height();获取页面可视高度 $(document).height();获取页面内容的总高度 $(document) ...

  9. nat和打洞

    http://michankong.blog.51cto.com/1464983/761270 可能有点乱,下面以故事的形式叙述一下这个情景. 人物:A(男) NAT_A(A家接线员) B(女) NA ...

  10. mac地址静态捆绑,防止arp欺骗

    arp -s 192.168.1.101 00-21-CC-D3-D5-FF 缺点,每次关机就还原,所以一般创建批处理文件,开机启动. ping 192.168.1.100 -l 65500 多台肉鸡 ...