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;
    }
};
相关推荐
All for pursuit.2 小时前
【动态规划-6】96.不同的二叉搜索树
数据结构·c++·算法·leetcode·动态规划
rou2 小时前
Attention(注意力机制)
算法
信奥卷王2 小时前
[GESP202609 六级] 数组划分
数据结构·算法
大鹏的NLP博客3 小时前
C++ 内存安全的未来:从 Safety Profiles 到 Safe C++
c++·内存安全
牧羊人.3333 小时前
动手学深度学习 07|Resnet网络与迁移学习
网络·人工智能·深度学习·神经网络·算法·cnn·迁移学习
程序员zgh3 小时前
C++ erase() 函数用法
c语言·开发语言·c++·学习
All for pursuit.4 小时前
【并查集-2】399.除法求值
数据结构·c++·算法·leetcode
迪丽热爱4 小时前
一、C语言概述与程序结构
c语言·开发语言·算法
码爸4 小时前
动态规划介绍
算法·动态规划