题解 | #最大子矩阵#

最大子矩阵

https://www.nowcoder.com/practice/a5a0b05f0505406ca837a3a76a5419b3

参考了其他大哥的思路,自己写的
基本思路是
1、求一维数组的最大子序列和
2、最大子矩阵有可能是1到n行,所以要遍历
3、为了遍历便捷性,增加一个辅助数组total[i][j] ,用来存放前第j列前i行的元素和

#include <stdio.h>

int fun(int* arr,int n);

int main(){
    int n = 0;
    scanf("%d",&n);
    int arr[n][n];
    int total[n][n];
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            //初始化辅助数组
            total[i][j] = 0;
        }
    }
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            scanf("%d",&arr[i][j]);
            //求辅助数组
            if(i == 0)
                total[i][j] = arr[i][j];
            else
                total[i][j] = total[i-1][j] + arr[i][j];
        }
    }
    
    //从一行到n行遍历
    int max = -999;
    int tmp = 0;
    int ass[n];
    for(int i = 0; i < n; i++){
        ass[i] = 0;
    }
    for(int i = 1; i <= n; i++){
        for(int j = i-1; j < n; j++){
            for(int k = 0; k < n; k++){
                if(j < i)
                    ass[k] = total[j][k];
                else
                    ass[k] = total[j][k] - total[j-i][k];
            }
            tmp = fun(ass,n);
            max = tmp > max ? tmp : max;
        }
    }
    printf("%d",max);
    return 0;
}

//一维数组求最大和
int fun(int* arr,int n){
    int max = 0;
    int prev = arr[0];
    max = prev;
    if(n == 1){
        return max;
    }
    for(int i = 1; i < n; i++){
        prev = (prev + arr[i]) > arr[i] ? (prev + arr[i]) : arr[i];
        max = max > prev ? max : prev;
    }
    return max;
}
全部评论

相关推荐

01-12 22:27
武汉大学 Java
点赞 评论 收藏
分享
01-03 10:04
已编辑
北京大学 算法工程师
北科勒布朗詹姆斯:无脑腾,现在户口有鸟用,你又不高考,研究所都是嘴上一套背后一套的,招人的时候说是37w955,真去了可由不得你
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务