Search code examples
c#javasummaxsubmatrix

Maximum Submatrix Sum of nxn matrices


I'm trying to get the maximum Submatrix Sum from given nxn matrices. From what I read around the algorithm have a complexity of n^3 (kadane). I tried to implement it in java using a code I found here on stackoverflow (written by Anders Gustafsson in C# in these post) but it seems to not always work.

my code is this:

public static void maxSubMatrix(int matrix[][]) {
    // O(n^3) Max Sum Submatrix

    int row = matrix.length;
    int col = matrix[0].length; // Get the col-length by taking the length of 
                                // row 0 (in programm the matrices will be n x n)

    // Initialise maxSum
    int maxSum = 0;

    // Set left column
    for (int left=0; left<col; left++) {

        // Initialise array
        int tempArray[] = new int[row];

        // Set right column by left column (outer loop)
        for (int right=left; right<col; right++){

            // Calculate sum between current left-right for every row 'i'
            for (int i=0; i<row; i++)
                tempArray[i] = matrix[i][right];
            // ----

            // Find maximum sum in tempArray[]
            int sum = maxSubArray(tempArray);

            // Compare sum with maxSum so far, and update it if necessary
            if (sum > maxSum) maxSum = sum;
        }
    }
    System.out.println(maxSum);
}
// ==========================

public static int maxSubArray(int array[]){
    // Kadane O(n) Max Sum Subarray
    int maxSum = 0;
    int tempSum = 0;

    for (int i=0; i<array.length; i++){
        int b = array[i];
        if (tempSum + b > 0) tempSum += b;
        else tempSum = 0;
        maxSum = Math.max(maxSum, tempSum);
    }
    return maxSum;
}

I have three examples:

Matrix 1
-2 -3
-1 -4
Output is 0 (Also the empty 0x0 Matrix is a solution)

Matrix 2
2 -1
-2 -1
Output is 2

Matrix 3
-1 3
3 -1
Output is 3, but should be 4

Maybe someone can see the error. I'm also open to completely new idea to implement it.


Solution

  • You have just forgotten to add the next rigth element to the temp-array:

    (int i=0; i<row; i++)
                tempArray[i] += matrix[i][right];
    

    Now everything's fine! ;)

    Greetz