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
原创粉丝点击