363. Max Sum of Rectangle No Larger Than K

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?

方法1: Kadane’s algorithm + binary search

discussion: https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/83599/Accepted-C%2B%2B-codes-with-explanation-and-references
Tushar: https://www.youtube.com/watch?v=yCQN096CwWM&feature=youtu.be

思路:

主体思路和上面视频中的kadane’s 一样,首先整体是以双层循环扫描每一列,也就是O(n ^ 2)。在每一次内层扫描中,计算一个row-wise的累计和vector,每次获得的vector,用largest substring 的方法找到行列都累加起来的累计和最大范围,更新left,right,up,down的index来记录全球最大。而每一次找largest substring的方法运用了binary search,来避免O(m ^ 2)。具体来讲:因为sums[i,j] = sums[i] - sums[j],then sums[i,j] is target subarray that needs to have sum <= k,sums[j] is known current cumulative sum。And we use binary search to find sums[i]. Therefore sums[i] needs to have sum >= sums[j] - k,复杂度降为O(m log m)。

Complexity

Time complexity: O[min(m,n)^2 * max(m,n) * log(max(m,n))]
Space complexity: O(max(m, n)).

class Solution {
public:
    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
        int m = matrix.size(), n = matrix[0].size();
        int res = INT_MIN;
        
        for (int l = 0; l < n; l++) {
            vector<int> rowsum(m, 0);
            for (int r = l; r < n; r++) {
                int sum = 0;
                set<int> sumset;
                // 首先应该将0 insert,那么当 curSum 和k相等时,0就可以被返回了。至少应该有0.
                sumset.insert(0);
                for (int i = 0; i < m; i++) {
                    rowsum[i] += matrix[i][r];
                    sum += rowsum[i];
                    
                    auto it = lower_bound(sumset.begin(), sumset.end(), sum - k);
                    if (it != sumset.end()) res = max(res, sum - *it);
                    // 必须在查找后插入,因为当k = 0 的情况,不应该包含自己
                    sumset.insert(sum);
                }
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值