【Leetcode】1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold

题目地址:

https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/description/

给定一个 m × n m\times n m×n的二维矩阵 A A A,再给定一个非负整数 t t t,问总和小于等于 t t t的子方阵中边长最大是多少。如果不存在则返回 0 0 0

先求 A A A的前缀和数组,这样方便迅速求得子方阵的和。直接枚举子方阵的右下角的点即可,如果发现了某个边长 r r r的子方阵的和小于等于 t t t,那么我们就知道了答案一定大于等于 r r r,从而我们枚举子方阵边长的时候可以单调的枚举,因为我们不必枚举更小的答案。代码如下:

class Solution {
 public:
  int maxSideLength(vector<vector<int>>& g, int threshold) {
    int m = g.size(), n = g[0].size();
    int s[m + 1][n + 1];
    memset(s, 0, sizeof s);
    for (int i = 1; i <= m; i++)
      for (int j = 1; j <= n; j++)
        s[i][j] = g[i - 1][j - 1] + s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1];
    auto f = [&](int x1, int y1, int x2, int y2) {
      return s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1];
    };
    int res = 0;
    for (int i = 1; i <= m; i++)
      for (int j = 1; j <= n; j++)
        for (int k = res + 1; k <= min(i, j); k++) {
          if (f(i - k + 1, j - k + 1, i, j) > threshold) break;
          res++;
        }
    return res;
  }
};

时空复杂度 O ( m n ) O(mn) O(mn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值