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:

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

  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?

Approach #1:

class Solution {
public:
    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
        int row = matrix.size();
        int col = matrix[0].size();
        int ans = INT_MIN;
        for (int i = 0; i < col; ++i) {
            vector<int> temp(row, 0);
            for (int j = i; j < col; ++j) {
                for (int k = 0; k < row; ++k) 
                    temp[k] += matrix[k][j];
                helper(temp, k, ans);
            }
        }
        return ans;
    }
    
    void helper(vector<int> temp, int k, int& ans) {
        int sum = 0;
        int cur_max = INT_MIN;
        set<int> s;
        s.insert(0);
        for (int i = 0; i < temp.size(); ++i) {
            sum += temp[i];
            auto it = s.lower_bound(sum-k);
            if (it != s.end()) cur_max = max(cur_max, sum - *it);
            s.insert(sum);
        }
        ans = max(ans, cur_max);
    }
};

Runtime: 172 ms, faster than 55.61% of C++ online submissions for Max Sum of Rectangle No Larger Than K.

here is a esay way to understand "largest sum of contiguous subarray No Larger than k"

private int maxSumSubArray(int[] a , int k){

    int max = Integer.MIN_VALUE;
    for(int i=0;i<a.length;i++){
        int tsum = 0;
        for(int j=i;j<a.length;j++){
            tsum += a[j];
            if(tsum <= k) max=Math.max(max,tsum);
        }
    }

    return max;
}

  

永远渴望,大智若愚(stay hungry, stay foolish)
原文地址:https://www.cnblogs.com/h-hkai/p/9906312.html