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;
    }
};
相关推荐
道尔柯南1 分钟前
C++ 内存管理详解:从 malloc/free 到 new/delete
c++·面试
東隅已逝,桑榆非晚6 分钟前
AVL数实现
c++·笔记·学习·算法
思想觉悟21 分钟前
SEAndroid实战
android·linux·c++
驭渊的小故事33 分钟前
LeetCode 算法题解:滑动窗口与数组合并的实战应用
算法·leetcode·职场和发展
.YM.Z36 分钟前
优选算法——【双指针算法2】C++实现
开发语言·c++·算法
逆向编程40 分钟前
MATLAB高级数据结构:cell、struct与table深度应用
开发语言·数据结构·matlab
思想觉悟41 分钟前
Aosp开发磨刀石之ADB速查
android·c++
小此方1 小时前
C++ 工程组件与基础设施(三)详解RPC服务的概念与安装,图片介绍Brpc服务器和客户端的搭建过程
服务器·c++·rpc
qq_406981031 小时前
什么是顶层 const什么是底层const
开发语言·c++
zwc32104320551 小时前
第四周第五天——重构成类
c++·人工智能·opencv·算法·计算机视觉