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. JSch - Java实现的SFTP

    JSch - Java实现的SFTP(文件上传详解篇)     JSch是Java Secure Channel的缩写.JSch是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以 ...

  2. android 没有main函数,怎么找到程序执行入口呢?以及activity主要生命周期的方法说明

    android应用程序,由一到多个Activity组成.每个Activity没有很紧密的联系,因为我们可以在自己的程序中调用其它Activity,特别是调用自己的代码之外生成的Activity,比如a ...

  3. ST Visual Programmer批量烧写教程

    源:ST Visual Programmer批量烧写教程 参考:为什么STM8 写了保护后,用ST Visual Programmer 无法重新烧录程序? 首先要说下为什么要建立烧写工程呢- -原因只 ...

  4. java HTTP请求 DefaultHttpClient is deprecated

    最近在使用Apache的httpclient的时候,maven引用了最新版本4.3,发现Idea提示DefaultHttpClient等常用的类已经不推荐使用了,之前在使用4.2.3版本的时候,还没有 ...

  5. Android性能优化典范---转

    Android性能优化典范 原文链接:  http://hukai.me/android-performance-patterns/ JAN 17TH, 2015 | COMMENTS 2015新年伊 ...

  6. Java对数函数及Java对数运算

    Java对数函数及Java对数运算 2010-05-17 10:32 中国IT实验室 佚名   关键字:Java   Java对数函数的计算方法非常有问题,然而在API中却有惊人的误差.但是假如运用了 ...

  7. (转)在Java中如何遍历Map对象

    在Java中如何遍历Map对象 How to Iterate Over a Map in Java 在java中遍历Map有不少的方法.我们看一下最常用的方法及其优缺点. 既然java中的所有map都 ...

  8. Linq to SQL 简单的增删改操作

    Linq to SQL 简单的增删改操作. 新建数据库表tbGuestBook.结构如下: 新建web项目,完成相应的dbml文件.留言页面布局如下 <body> <form id= ...

  9. 关于val(),text(),html()的用法

    直接上demo: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ww ...

  10. OpenCV学习(20) grabcut分割算法

    http://www.cnblogs.com/mikewolf2002/p/3330390.html OpenCV学习(20) grabcut分割算法 在OpenCV中,实现了grabcut分割算法, ...