-2

Given a matrix with m-rows and n-columns, finding the maximum sum of elements in the matrix by removing almost one row or one column

Example: 
m=2, n=3

matrix : 
**[[1,2,-3]
[4,5,-6 ]
]**

output: 12 , by removing the third column then sum of elements in
[[1,2][4,5]]

How to solve this problem in java8 using dynamic programming

1 Answers1

0

Based on the kadane algorithm, below code works fine

public static void main(String[] args) {
    int[][] m = {
            {1, 2, -3},
            {4, 5, -5},
    };
    int N = m.length;

    for (int i = 0; i < N; ++i)
        m[0][i] = m[0][i];
    for (int j = 1; j < N; ++j)
        for (int i = 0; i < N; ++i)
            m[j][i] = m[j][i] + m[j - 1][i];

    int totalMaxSum = 0, sum;
    for (int i = 0; i < N; ++i) {
        for (int k = i; k < N; ++k) {
            sum = 0;
            for (int j = 0; j < N; j++) {
                sum += i == 0 ? m[k][j] : m[k][j] - m[i - 1][j];
                totalMaxSum = Math.max(sum, totalMaxSum);
            }
        }
    }

    System.out.println(totalMaxSum);
}