944 · 最大子矩阵(前缀和)

链接:LintCode 炼码 - 更高效的学习体验!

题解:

cpp 复制代码
class Solution {
public:
    /**
     * @param matrix: the given matrix
     * @return: the largest possible sum
     */
    int maxSubmatrix(vector<vector<int>> &matrix) {
        // write your code here
        int m = matrix.size();
        if (m <= 0) {
            return 0;
        }
        int n = matrix[0].size();
        if (n <= 0) {
            return 0;
        }
        vector<vector<int>> prefix(m+1, vector<int>(n+1, 0));
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                prefix[i+1][j+1] = prefix[i][j+1] + prefix[i+1][j] - prefix[i][j] + matrix[i][j];
            }
        }
        int result = INT_MIN;
        for (int top = 0; top < m; ++top) {
            for (int bottom = top; bottom < m; ++bottom) {
                int min_sum = 0;
                for (int i = 0; i < n; ++i) {
                   int tmp = prefix[bottom+1][i+1] - prefix[top][i+1];
                   result = max(result, tmp-min_sum);
                   min_sum = min(min_sum, tmp);
                }
            }
        }
        return result;
    }
};
相关推荐
console.log('npc')1 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
eggwyw1 小时前
C++设计模式之解释器模式
开发语言·c++
橘子132 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘13 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
我不会插花弄玉15 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴16 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David16 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
西西弗Sisyphus17 小时前
C++ explicit 关键字工程实践
开发语言·c++
Pniubi19 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK20 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set