[leetcode] 363. Max Sum of Rectangle No Larger Than K

网友投稿 271 2022-08-27

[leetcode] 363. Max Sum of Rectangle No Larger Than K

Description

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:

Input: matrix = [[1,0,1],[0,-2,3]], k = 2Output: 2 Explanation: 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?

分析

题目的意思是:给你一个矩阵和k,找出其中一个最大子矩阵使得这个子矩阵求和不大于k。

遍历所有的子矩形,然后计算其和跟K比较,找出不超过K的最大值即可。当遍历到(i, j)时,我们计算sum(i, j),表示矩形(0, 0)到(i, j)的和,然后我们遍历这个矩形中所有的子矩形,计算其和跟K相比,这样可遍历到原矩形的所有子矩形。

代码

class Solution {public: int maxSumSubmatrix(vector>& matrix, int k) { if(matrix.empty()||matrix[0].empty()){ return 0; } int m=matrix.size(),n=matrix[0].size(); int sum[m][n]; int res=INT_MIN; for(int i=0;i0) t+=sum[i-1][j]; if(j>0) t+=sum[i][j-1]; if(i>0&&j>0) t-=sum[i-1][j-1]; sum[i][j]=t; for(int r=0;r<=i;r++){ for(int c=0;c<=j;c++){ int d=sum[i][j]; if(r>0) d-=sum[r-1][j]; if(c>0) d-=sum[i][c-1]; if(r>0&&c>0){ d+=sum[r-1][c-1]; } if(d<=k){ res=max(res,d); } } } } } return res; }};

参考文献

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 221. Maximal Square
下一篇:金融消费者如何防范营销“套路”?(金融产品营销技巧)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~