leetcode 363. Max Sum of Rectangle No Larger Than K 动态规划DP + 暴力循环
来源:互联网 发布:揭阳网络广告公司 编辑:程序博客网 时间:2024/06/16 13:47
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?
没有想到更好地做法,我这里直接暴力求解。效果还不错,accept了。
代码如下:
import java.util.TreeSet;class Solution { /* * 暴力做法很定不好,但是暂时想不到更好的办法,所以先这么办吧 * */ public int maxSumSubmatrix(int[][] matrix, int k) { if(matrix==null || matrix.length<=0) return 0; int[][] sum=new int[matrix.length+1][matrix[0].length+1]; for(int i=1;i<=matrix.length;i++) for(int j=1;j<=matrix[0].length;j++) sum[i][j]=matrix[i-1][j-1]+sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]; int max=Integer.MIN_VALUE; for(int i=1;i<=matrix.length;i++) { for(int j=1;j<=matrix[0].length;j++) { for(int g=0;g<i;g++) { for(int h=0;h<j;h++) { int one=sum[i][j]-(sum[i][h]+sum[g][j]-sum[g][h]); if(one<=k) max = Math.max(max, one); } } } } return max; }}
阅读全文
0 0
- leetcode 363. Max Sum of Rectangle No Larger Than K 动态规划DP + 暴力循环
- [leetcode] 363. Max Sum of Rectangle No Larger Than K
- leetcode.363. Max Sum of Rectangle No Larger Than K
- [LeetCode]--363. Max Sum of Rectangle No Larger Than K
- leetcode-363. Max Sum of Rectangle No Larger Than K
- Leetcode 363. Max Sum of Rectangle No Larger Than K
- 【Leetcode】363. Max Sum of Rectangle No Larger Than K
- [leetcode]363. Max Sum of Rectangle No Larger Than K
- leetcode 363. Max Sum of Rectangle No Larger Than K
- Leetcode Max Sum of Rectangle No Larger Than K
- [LeetCode]Max Sum of Rectangle No Larger Than K
- leetcode(363):Max Sum of Rectangle No Larger Than K
- [LeetCode] Max Sum of Rectangle No Larger Than K
- 【Leetcode】Max Sum of Rectangle No Larger Than K
- 363. Max Sum of Rectangle No Larger Than K
- 363. Max Sum of Rectangle No Larger Than K[hard]
- 363. Max Sum of Rectangle No Larger Than K
- 363. Max Sum of Rectangle No Larger Than K
- abc
- Android O中Notification 的修改与其使用错误
- what a fuck!这是什么鬼东西?
- UVA
- 欧拉函数求和
- leetcode 363. Max Sum of Rectangle No Larger Than K 动态规划DP + 暴力循环
- POJ 2186 Popular Cows 笔记
- 如何解决maven搭建项目的时候,src/main/java无法建立的问题,提示信息The folder is already a source folder.
- qt不同窗口之间的切换
- 简单利用RecyclerView实现ListView的点击事件
- Could not load TestContextBootstrapper [null]. Specify @BootstrapWith's 'val
- ie的png透明图片兼容性问题
- js鼠标滚动 mousewheel
- JS各循环的差别