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. oracle xe client 如何设置 tnsnames.ora(解决无法使用pl/sql developer的问题)

    10.2版本xe的服务器和客户端安装都很方便,由于xe的服务器只允许建立一个实例,实例名字会直接默认为xe,客户端默认安装在C:\XEClient目录下,使用sqlplus连接服务器: sqlplus ...

  2. IOS小工具以及精彩的博客

    IOS小工具以及精彩的博客 工具 Log Guru是一个收集Log的小工具, 可以在 Mac 上查看 iOS 设备的实时系统日志. 现在可以直接高亮显示在 FIR.im 上安装 app 失败的原因.后 ...

  3. 6-SUPER关键字

    (1)强行调用父类方法的执行(2)super不一定在重写中使用,也可以表示那些方法是从父类中继承而来的.

  4. PHP中require()文件包含的正确用法

    以前看一些PHP框架源码的时候,很奇怪在文件包含的时候,会用dirname(__FILE__)来拼凑文件路 径,不知道这样做有什么好处,后来终于发现了其中的缘由. 我们来看一个简单的例子: 有a,b, ...

  5. 写入cookie后只显示一次的DIV提示框代码

    <script type="text/javascript"> function cookiesave(n, v, mins, dn, path){ if(n) { i ...

  6. MyEclipse9,MyEclipse10 安装ADT

    Eclipse安装ADT 时步骤是开 Eclipse IDE,进入菜单中的 "Help" -> "Install New Software" ,点击Add ...

  7. Android Fragment 真正的完全解析(上)--转

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37970961 自从Fragment出现,曾经有段时间,感觉大家谈什么都能跟Fra ...

  8. Divisor Summation_

    Divisor Summation Problem Description Give a natural number n (1 <= n <= 500000), please tell ...

  9. 转:WebDriver(Selenium2)模拟鼠标经过事件

    在自动化测试过程中,由于javascript的使用,我们常常需要点击一些鼠标经过显示的菜单等元素,这时需要触发该元素的鼠标经过事件.使用WebDriver有以下两种实现. 1.使用Action pub ...

  10. CSS3中transform几个属性值的注意点

    transform(变形)是CSS3中的元素的属性,transform的属性值主要包括旋转rotate.扭曲skew.缩放scale和移动translate以及矩阵变形matrix 基本用法可以参考文 ...