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 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:
The rectangle inside the matrix must have an area > 0.
What if the number of rows is much larger than the number of columns?
Reference: https://discuss.leetcode.com/topic/48875/accepted-c-codes-with-explanation-and-references/2
The naive solution is brute-force, which is O((mn)^2). In order to be more efficient, I tried something similar to Kadane's algorithm. The only difference is that here we have upper bound restriction K.
First, How to find the max sum rectangle in 2D array? The naive way is O(N^4)
Here's the easily understanding video link for the problem "find the max sum rectangle in 2D array": Maximum Sum Rectangular Submatrix in Matrix dynamic programming/2D kadane , O(N^3), the idea is select left edge l and right edge r, together with top edge 0 and bottom edge n, form a subrectangle area, (O(N^2)), find the local max sum in this subrectangle, just like max sum subarray(O(N). So the total time complexity is O(N^3), space complexity is O(N).
Once you are clear how to solve the above problem, the next step is to find the max sum no more than K in an array. This can be done within O(nlogn), and you can refer to this article: max subarray sum no more than k.
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 bigger than cum[j]−k. This lookup can be done in O(logn) using upper_bound. Hence the overall complexity is O(nlog(n)).
This can be done using TreeSet.
For the solution below, I assume that the number of rows is larger than the number of columns. Thus in general time complexity is
O[min(m,n)^2 * max(m,n) * log(max(m,n))], space O(max(m, n)).
假设col<row,下面的意思就是维护一个size为row的 sum数组。 每次iteration这个sum数组用来存某几个col叠加在一起的和(就是某一个rectangle的sum),然后在其中用treeSet找出当前最大的rectangle sum,时间复杂度是row*(log(row)). 所有iteration完成就得到最终答案,iteration数目是O(col^2), 所以总时间复杂度是O(col^2*row*log(row))。
例子:
1 2 3
4 5 6
7 8 9
假如现在i = 0, j=1, 那么当前subrectangle是[[1, 2], [4, 5], [7, 8]], 于是int[] sum就是[[1+2], [4+5], [7+8]] = [[3], [9], [15]], val是这个sum数组的preSum, 依次取的值是3, 3+9=12, 3+9+15=27, 所以TreeSet里面依次被加入0,3,12,27. 假设k=16,那么到27的时候,set里面是0,3,12,存在比27-16=11大的值是12,说明存在不大于k=16的最大subrectangle area = 27-12=15
Time Complexity: O[min(m,n)^2 * max(m,n) * log(max(m,n))], space O(max(m, n)). compare to naive solution time complexity O((mn)^2)
same as Leetcode: Number of Submatrices That Sum to Target
public class Solution {
public int maxSumSubmatrix(int[][] matrix, int k) {
if (matrix==null || matrix.length==0 || matrix[0].length==0) return Integer.MIN_VALUE;
int res = Integer.MIN_VALUE; int row = matrix.length;
int col = matrix[0].length;
int m = Math.min(row, col);
int n= Math.max(row, col);
boolean moreCol = col > row; for (int i=0; i<m; i++) {
int[] sum = new int[n];
for (int j=i; j<m; j++) {
TreeSet<Integer> set = new TreeSet<Integer>();
int val = 0; //sum array's preSum
set.add(0);
for (int l=0; l<n; l++) {
sum[l] += moreCol? matrix[j][l] : matrix[l][j];
val += sum[l];
Integer oneSum = set.ceiling(val-k);
if (oneSum != null) {
res = Math.max(res, val-oneSum);
}
set.add(val);
}
}
}
return res;
}
}
Leetcode: Max Sum of Rectangle No Larger Than K的更多相关文章
- [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 ...
- 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 ...
- [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 ...
- 【LeetCode】363. Max Sum of Rectangle No Larger Than K 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/max-sum- ...
- 【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 ...
- [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 ...
- 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 ...
- 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 ...
- LeetCode 363:Max Sum of Rectangle No Larger Than K
题目链接 链接:https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/ 题解&代码 1 ...
随机推荐
- delphi 数组类型与数组指针的巧妙利用
{本例通过存取结构, 慢慢引入了数组类型与指针的一些使用方法; 其中六个小例子的测试内容和结果都是一样的. ---------------------------------------------- ...
- js中json字符串转成js对象
json字符串转成js对象我所知的方法有2种: //json字符串转换成json对象 var str_json = "{name:'liuchuan'}"; //json字符串 / ...
- nginx proxy_pass
在nginx中配置proxy_pass时,如果是按照^~匹配路径时,要注意proxy_pass后的url最后的/,当加上了/,相当于是绝对根路径,则nginx不会把location中匹配的路径部分代理 ...
- jboss4.2.3建立oracle JMS应用
一.基本配置 1 增加oracle驱动文件,ojdbc6.jar,不能使用小于该版本的jdbc驱动,jboss-4.2.3.GA\server\default\lib 2 增加retrotransla ...
- php 请求参数限制
公司有个群发短信的小项目,项目上线了很久也没有什么问题,最近有商家说 我短信群发不能用 现象是:发现有时候可以发送,有时候不可以发送,看截图发送的手机数量不一样 通过调试php代码发现 php 只接受 ...
- 应用github pages创建自己的个人博客
首先你需要注册自己的github账号 1.登录或者注册github,登录之后点击右上角的“+”号,选择“New repository”菜单,创建仓库,用于存储和博客相关的源文件. 2.跳转页面将填写域 ...
- 使用Nginx在自己的电脑上实现负载均衡
我其实早就想弄这个负载均衡了,但是总觉得这玩意肯定不简单,今天星期六闲着没事终于下定决心来搞一搞他了,但是没想到这玩意这么简单,真的是出乎我的意料的简单(我现在陪的是最简单的那种).额是没有我想象中的 ...
- C# where(泛型类型约束)
/*在泛型类型定义中,where 子句用于指定对下列类型的约束:这些类型可用作泛型声明中定义的类型参数的实参. 例如,可以声明一个泛型类 MyGenericClass,这样,类型参数 T 就可以实现 ...
- TCP connection status
A TCP connection progresses through a series of states during its lifetime. The following diagram il ...
- 修改OpenCart系统配置
后台修改admin配置文件和修改根目录下的config.php <?php// HTTPdefine('HTTP_SERVER', 'http://网站域名/');define('HTTP_IM ...