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. WebSphere MQ 入门指南【转】

    WebSphere MQ 入门指南 转自 WebSphere MQ 入门指南 - 大CC - 博客园http://www.cnblogs.com/me115/p/3456407.html 这是一篇入门 ...

  2. 低电压锁定(UVLO) (转)

    源:http://blog.csdn.net/zhenwenxian/article/details/8523307 UVLO就是低电压锁定: 低压关断. 欠压关断模式是当供电电压低于IC的开启门限电 ...

  3. ListView下拉刷新、上拉载入更多之封装改进

    在Android中ListView下拉刷新.上拉载入更多示例一文中,Maxwin兄给出的控件比较强大,前面有详细介绍,但是有个不足就是,里面使用了一些资源文件,包括图片,String,layout,这 ...

  4. jaxb异常 Class has two properties of the same name username

    import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; im ...

  5. 分析UIWindow

    转载自:http://www.cnblogs.com/YouXianMing/p/3811741.html The UIWindow class defines an object known as ...

  6. 5个简单的步骤把 WordPress 打造成 CMS

    可能网站的首页一直是一成不变的博客样子,有时候也会挺闷的,个人觉得首页就是应该把博客中最好最重要的内容展现给读者,基于这个想法,我们可以把博客的首页改成一个非常简单的 CMS 首页. 基于 WordP ...

  7. Asp获取网址相关参数大全

      Asp获取网址相关参数大全 代码一:[获取地址中的文件名,不包含扩展名]<%dim Url,FileName,File Url=split(request.servervariables(& ...

  8. js中:Date.utc()方法与getTime()方法返回值不相等的原因

    // Date.UTC() 方法接受的参数同日期构造函数接受最多参数时一样,返回从1970-1-1 00:00:00 UTC到指定日期的的毫秒数. var utcDate = Date.UTC(201 ...

  9. 多元线性回归----Java简单实现

    http://www.cnblogs.com/wzm-xu/p/4062266.html 多元线性回归----Java简单实现   学习Andrew N.g的机器学习课程之后的简单实现. 课程地址:h ...

  10. TCP四次挥手

    TCP 四次挥手      TCP的连接的拆除需要发送四个包,因此称为四次挥手(four-way handshake).客户端或服务器均可主动发起挥手动作,在socket编程中,任何一方执行close ...