面试题 17.24. 最大子矩阵

链接:

面试题 17.24. 最大子矩阵

题解:

这样我们就将二维问题转化为了一维问题,现在另一个问题就是怎么把所有情况都遍历到呢?

我们以第i行为第一行,向下延申,设最后一行为第j行,我们就i在这么一个范围内,将二维问题转化为一维问题,再求解最大子序列和

作者:bugsmaker
链接:https://leetcode.cn/problems/max-submatrix-lcci/solutions/137568/zhe-yao-cong-zui-da-zi-xu-he-shuo-qi-you-jian-dao-/

left,right,top,bottom分别是左右上下的矩阵边界

class Solution {
public:
    vector<int> getMaxMatrix(vector<vector<int>>& matrix) {
        int m = matrix.size();
        if (m <= 0) {
            return {};
        }
        int n = matrix[0].size();
        if (n <= 0) {
            return {};
        }
        std::vector<int> result(4);
        std::vector<std::vector<int>> prefix_sum(m+1, std::vector<int>(n+1, 0));
        // prefix[i][j] 表示以(i-1, j-1) 为右下角顶点的,(0, 0)左上角顶点矩阵的和
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                prefix_sum[i][j] = matrix[i-1][j-1] + prefix_sum[i][j-1] + prefix_sum[i-1][j] - prefix_sum[i-1][j-1]; 
            }
        }
        int global_max = INT_MIN;
        // 枚举上边界
        for (int top = 0; top < m; ++top) {
            // 枚举下边界
            for (int bottom = top; bottom < m; ++bottom) {
                int local_max = 0;
                int left = 0;
                // 枚举最右边的列,获得窗口
                for (int right = 0; right < n; ++right) {
                    // 获得当前窗口的的数值
                    local_max = prefix_sum[bottom+1][right+1] - prefix_sum[bottom+1][left] -prefix_sum[top][right+1] + prefix_sum[top][left];
                    // 如果比最大值大,则更新最大值,保存结果
                    if (local_max > global_max) {
                        global_max = local_max;
                        result[0] = top;
                        result[1] = left;
                        result[2] = bottom;
                        result[3] = right;
                    }
                    // 如果当前窗口已经变为负数,则更新窗口的左端点
                    if (local_max < 0) {
                        local_max = 0;
                        left = right + 1;
                    }
                }
            }            
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值