1. 程式人生 > >Leetcode: Max Sum of Rectangle No Larger Than K

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.

Note:

  1. The rectangle inside the matrix must have an area > 0. (1 也算)
  2. What if the number of rows is much larger than the number of columns?

最大子序列問題的二維擴充套件版本。直接Brute Force。

class Solution { public:     int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {         int height = matrix.size();         int width = matrix[0].size();         int currentmax = INT_MIN; //numeric_limits<int>::min();         vector<vector<int>> sum(height, vector<int>(width,0));         for(int i=0;i<height;i++){             for(int j=0;j<width;j++){                 if(i>0){sum[i][j] += sum[i-1][j];}                 if(j>0){sum[i][j] += sum[i][j-1];}                 if(i>0 && j>0){sum[i][j] -= sum[i-1][j-1];}                 sum[i][j] += matrix[i][j];// 二維矩陣求和matrix[0:i][0:j],利用已經計算出的矩陣                  for(int r=0;r<=i;r++){                     for(int m=0;m<=j;m++){                         int res = sum[i][j];                         if(r>0) res -= sum[r-1][j];                         if(m>0) res -= sum[i][m-1];                         if(r>0 && m>0){res += sum[r-1][m-1];}//二維子矩陣求和matrix[r:i][m:j],利用已經計算出的矩陣                          if(res<=k && res>currentmax) currentmax = res;                     }                 }             }         }         return currentmax;     } };

hints:Jay kadane: 可以用二維的kadane 演算法進一步優化,但是不用也可以在時間複雜度要求範圍內解決問題。