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 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?

Credits:

Special thanks to @fujiaozhu for adding this problem and creating all test cases.



摘自

https://discuss.leetcode.com/topic/48875/accepted-c-codes-with-explanation-and-references/4

http://www.cnblogs.com/fll/archive/2008/05/17/1201543.html


先看一下最大子矩阵问题。


给定一个n*n(0<n<=100)的矩阵,请找到此矩阵的一个子矩阵,并且此子矩阵的各个元素的和最大,输出这个最大的值。
Example:
 0 -2 -7  0 
 9  2 -6  2 
-4  1 -4  1 
-1  8  0 -2 
其中左上角的子矩阵:
 9 2 
-4 1 
-1 8 
此子矩阵的值为9+2+(-4)+1+(-1)+8=15。
  我们首先想到的方法就是穷举一个矩阵的所有子矩阵,然而一个n*n的矩阵的子矩阵的个数当n比较大时时一个很大的数字 O(n^2*n^2),显然此方法不可行。
  怎么使得问题的复杂度降低呢?对了,相信大家应该知道了,用动态规划。对于此题,怎么使用动态规划呢?

  让我们先来看另外的一个问题(最大子段和问题):
    给定一个长度为n的一维数组a,请找出此数组的一个子数组,使得此子数组的和sum=a[i]+a[i+1]+……+a[j]最大,其中i>=0,i<n,j>=i,j<n,例如
   31 -41 59 26 -53  58 97 -93 -23 84
 子矩阵59+26-53+58+97=187为所求的最大子数组。
第一种方法-直接穷举法:
   maxsofar=0;
   for i = 0 to n
   {
       for  j = i to n 
       {
            sum=0;
            for k=i to j 
                sum+=a[k] 
            if (maxsofar>sum)
               maxsofar=sum;
       }
   }

第二种方法-带记忆的递推法:
   cumarr[0]=a[0]
   for i=1 to n      //首先生成一些部分和
   {
        cumarr[i]=cumarr[i-1]+a[i];       
   }

   maxsofar=0
   for i=0 to n
   {
       for  j=i to n     //下面通过已有的和递推
       {
           sum=cumarr[j]-cumarr[i-1]
           if(sum>maxsofar)
               maxsofar=sum
       }
   }
显然第二种方法比第一种方法有所改进,时间复杂度为O(n*n)。

下面我们来分析一下最大子段和的子结构,令b[j]表示从a[0]~a[j]的最大子段和,b[j]的当前值只有两种情况,(1) 最大子段一直连续到a[j]  (2) 以a[j]为起点的子段,不知有没有读者注意到还有一种情况,那就是最大字段没有包含a[j],如果没有包含a[j]的话,那么在算b[j]之前的时候我们已经算出来了,注意我们只是算到位置为j的地方,所以最大子断在a[j]后面的情况我们可以暂时不考虑。
由此我们得出b[j]的状态转移方程为:b[j]=max{b[j-1]+a[j],a[j]},
所求的最大子断和为max{b[j],0<=j<n}。进一步我们可以将b[]数组用一个变量代替。
得出的算法如下:
    int maxSubArray(int n,int a[])
    {
        int b=0,sum=-10000000;
        for(int i=0;i<n;i++)
        {
             if(b>0) b+=a[i];
             else b=a[i];
             if(b>sum) sum=b;  
        }
        return sum;
    }
这就是第三种方法-动态规划。


  现在回到我们的最初的最大子矩阵的问题,这个问题与上面所提到的最大子断有什么联系呢?
  假设最大子矩阵的结果为从第r行到k行、从第i列到j列的子矩阵,如下所示(ari表示a[r][i],假设数组下标从1开始):
  | a11 …… a1i ……a1j ……a1n |
  | a21 …… a2i ……a2j ……a2n |
  |  .     .     .    .    .     .    .   |
  |  .     .     .    .    .     .    .   |
  | ar1 …… ari ……arj ……arn |
  |  .     .     .    .    .     .    .   |
  |  .     .     .    .    .     .    .   |
  | ak1 …… aki ……akj ……akn |
  |  .     .     .    .    .     .    .   |
  | an1 …… ani ……anj ……ann |

 那么我们将从第r行到第k行的每一行中相同列的加起来,可以得到一个一维数组如下:
 (ar1+……+ak1, ar2+……+ak2, ……,arn+……+akn)
 由此我们可以看出最后所求的就是此一维数组的最大子断和问题,到此我们已经将问题转化为上面的已经解决了的问题了。

此题的详细解答如下(Java描述):

import java.util.Scanner;
public class PKU_1050
{
     private int maxSubArray(int n,int a[])
      {
            int b=0,sum=-10000000;
            for(int i=0;i<n;i++)
            {
                  if(b>0) b+=a[i];
                  else b=a[i];
                  if(b>sum) sum=b;
            }
            return sum;  
      }
      private int maxSubMatrix(int n,int[][] array)
      {
            int i,j,k,max=0,sum=-100000000;
            int b[]=new int[101];
            for(i=0;i<n;i++)
            {
                  for(k=0;k<n;k++)//初始化b[]
                  {
                        b[k]=0;
                  }
                  for(j=i;j<n;j++)//把第i行到第j行相加,对每一次相加求出最大值
                  {
                        for(k=0;k<n;k++)
                        {
                              b[k]+=array[j][k];
                        }
                        max=maxSubArray(k,b);  
                        if(max>sum)
                        {
                                sum=max;
                        }
                  }
            }
            return sum;
      }
      public static void main(String args[])
      {
            PKU_1050 p=new PKU_1050();
            Scanner cin=new Scanner(System.in);
            int n=0;
            int[][] array=new int[101][101];
            while(cin.hasNext())
            {
                       n=cin.nextInt();   
                       for(int i=0;i<n;i++)
                       {
                                  for(int j=0;j<n;j++)
                                  {
                                             array[i][j]=cin.nextInt();
                                  }
                       }
                       System.out.println(p.maxSubMatrix(n,array));
            }
      }
}



这里有限制,和不能超过K,又要最接近,参考问题


find a subarray that contains the largest sum, constraint that sum is less than k


把一维当中求最大子序列和替换为这个问题的解,2维到1维的处理过程不变。

public int maxSumSubmatrix(int[][] matrix, int k) {
    //2D Kadane's algorithm + 1D maxSum problem with sum limit k
    //2D subarray sum solution
    
    //boundary check
    if(matrix.length == 0) return 0;
    
    int m = matrix.length, n = matrix[0].length;
    int result = Integer.MIN_VALUE;
    
    //outer loop should use smaller axis
    //now we assume we have more rows than cols, therefore outer loop will be based on cols 
    for(int left = 0; left < n; left++){
        //array that accumulate sums for each row from left to right 
        int[] sums = new int[m];
        for(int right = left; right < n; right++){
            //update sums[] to include values in curr right col
            for(int i = 0; i < m; i++){
                sums[i] += matrix[i][right];
            }
            
            //we use TreeSet to help us find the rectangle with maxSum <= k with O(logN) time
            TreeSet<Integer> set = new TreeSet<Integer>();
            //add 0 to cover the single row case
            set.add(0);
            int currSum = 0;
            
            for(int sum : sums){
                currSum += sum;
                //we use sum subtraction (curSum - sum) to get the subarray with sum <= k
                //therefore we need to look for the smallest sum >= currSum - k
                Integer num = set.ceiling(currSum - k);
                if(num != null) result = Math.max( result, currSum - num );
                set.add(currSum);
            }
        }
    }
    
    return result;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值