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.

Analysis:

the function helper maybe difficult to understand, we suppose the temp array is [2, 8, 1, 5] ans k = 8:

猜你喜欢

转载自www.cnblogs.com/ruruozhenhao/p/9906312.html