classSolution { public: intmaxSumSubmatrix(vector<vector<int>> &matrix, int k){ int ans = INT_MIN; int m = matrix.size(), n = matrix[0].size(); for (int i = 0; i < m; ++i) { // 枚举上边界 vector<int> sum(n); for (int j = i; j < m; ++j) { // 枚举下边界 for (int c = 0; c < n; ++c) { sum[c] += matrix[j][c]; // 更新每列的元素和 } set<int> sumSet{0}; int s = 0; for (int v : sum) { s += v; auto lb = sumSet.lower_bound(s - k); if (lb != sumSet.end()) { ans = max(ans, s - *lb); } sumSet.insert(s); } } } return ans; } };
func(t *treap) lowerBound(val int) (lb *node) { for o := t.root; o != nil; { switch c := o.cmp(val); { case c == 0: lb = o o = o.ch[0] case c > 0: o = o.ch[1] default: return o } } return }
funcmaxSumSubmatrix(matrix [][]int, k int)int { ans := math.MinInt64 for i := range matrix { // 枚举上边界 sum := make([]int, len(matrix[0])) for _, row := range matrix[i:] { // 枚举下边界 for c, v := range row { sum[c] += v // 更新每列的元素和 } t := &treap{} t.put(0) s := 0 for _, v := range sum { s += v if lb := t.lowerBound(s - k); lb != nil { ans = max(ans, s-lb.val) } t.put(s) } } } return ans }
funcmax(a, b int)int { if a > b { return a } return b }
classSolution: defmaxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int: ans = float("-inf") m, n = len(matrix), len(matrix[0])
for i inrange(m): # 枚举上边界 total = [0] * n for j inrange(i, m): # 枚举下边界 for c inrange(n): total[c] += matrix[j][c] # 更新每列的元素和 totalSet = SortedList([0]) s = 0 for v in total: s += v lb = totalSet.bisect_left(s - k) if lb != len(totalSet): ans = max(ans, s - totalSet[lb]) totalSet.add(s)