Maximum Submatrix

2018-06-28  本文已影响10人  Frank_Kivi

https://www.lintcode.com/problem/maximum-submatrix/description

public class Solution {
    /**
     * @param matrix: the given matrix
     * @return: the largest possible sum
     */
    public int maxSubmatrix(int[][] matrix) {
        // write your code here
        if (matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        int[][] sumMatrix = new int[matrix.length + 1][matrix[0].length];
        for (int i = 0; i < matrix.length; i++) {
            int[] ints = matrix[i];
            for (int j = 0; j < ints.length; j++) {
                int anInt = ints[j];
                sumMatrix[i + 1][j] = sumMatrix[i][j] + anInt;
            }
        }
        int result = Integer.MIN_VALUE;
        for (int top = 1; top < sumMatrix.length; top++) {
            for (int bottom = top; bottom < sumMatrix.length; bottom++) {
                int[] compression = getCompression(sumMatrix, top, bottom);
                result = Math.max(result, getMax(compression));
            }
        }
        return result;
    }

    private int getMax(int[] compression) {
        int min = 0;
        int max = Integer.MIN_VALUE;
        int sum = 0;
        for (int i = 0; i < compression.length; i++) {
            int i1 = compression[i];
            sum += i1;
            min = Math.min(sum, min);
            max = Math.max(max, sum - min);
        }
        return max;
    }

    private int[] getCompression(int[][] sumMatrix, int top, int bottom) {
        int[] dp = new int[sumMatrix[0].length];
        for (int i = 0; i < dp.length; i++) {
            dp[i] = sumMatrix[bottom][i] - sumMatrix[top - 1][i];
        }
        return dp;
    }
}
上一篇下一篇

猜你喜欢

热点阅读