最大子矩阵和(dp)

import java.util.*;
public class Main {
    static long maxvalue(long[] a) {
        long max = Long.MIN_VALUE;
        for (int i = 1; i < a.length; i++) {
            a[i] = Math.max(a[i - 1] + a[i], a[i]);
            if (a[i] > max) max = a[i];
        }
        return max;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int M = sc.nextInt();
        int N = sc.nextInt(); //N行,M列。
        long[][] a = new long[N][M];
        long[][] total = new long[N][M];
        for (int i = 0; i < N; i++)
            for (int j = 0; j < M; j++)
                a[i][j] = sc.nextLong();
        total = a; //复制原始矩阵
        for (int i = 1; i < N; i++)
            for (int j = 0; j < M; j++)
                total[i][j] += total[i - 1][j]; //每行叠加
        long max = Long.MIN_VALUE;
        for (int i = 0; i < N; i++) //获取任意两行
            for (int j = i ; j < N; j++) {
                long[] result = new long[M]; //存各种行压缩之后的数
                for(int k = 0; k < M; k++) {
                    if (i == 0)
                        result[k] = total[j][k];
                    else result[k] = total[j][k] - total[i - 1][k];
//                    System.out.print(result[k] + " ");
                }
//                System.out.println();
                long maxx = maxvalue(result); //获取result的最大子序列
                if (maxx > max) max = maxx;
            }
        if (max < 0) System.out.println(0);
        else System.out.println(max);
    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页