aboutsummaryrefslogtreecommitdiff
path: root/max_sum_rectangle.cpp
blob: 9b252e10fc65a0d5aecddefdc00b5f3cd2a8405b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "leetcode.h"

class Solution {
public:
  int maxSumSubmatrix(vector<vector<int>> &matrix, int k) {
    int ans = INT_MIN, rows = matrix.size(), cols = matrix[0].size();
    for (int l = 0; l < cols; ++l) {
      vector<int> sums(rows);
      for (int r = l; r < cols; ++r) {
        int pMin = 0, pMax = INT_MIN;
        for (int i = 0; i < rows; ++i) {
          sums[i] += matrix[i][r];
          pMin = max(pMin + sums[i], sums[i]);
          pMax = max(pMax, pMin);
        }
        if (pMax <= k) {
          ans = max(ans, pMax);
          continue;
        }
        set<int> s = {0};
        int runSum = 0;
        for (int sum : sums) {
          runSum += sum;
          auto it = s.lower_bound(runSum - k);
          if (it != end(s))
            ans = max(ans, runSum - *it);
          s.insert(runSum);
        }
      }
    }
    return ans;
  }
};