【问题标题】:Maximum Submatrix Sum of nxn matricesnxn 矩阵的最大子矩阵和
【发布时间】:2014-03-08 16:01:26
【问题描述】:

我试图从给定的 nxn 矩阵中获得最大的子矩阵总和。从我读到的算法的复杂性为 n^3(kadane)。我尝试使用我在 stackoverflow 上找到的代码(由 Anders Gustafsson 用 C#in these post 编写)在 java 中实现它,但它似乎并不总是有效。

我的代码是这样的:

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;
}

我举了三个例子:

矩阵 1
-2 -3
-1 -4
输出为 0(空的 0x0 矩阵也是一种解决方案)

矩阵 2
2 -1
-2 -1
输出为 2

矩阵 3
-1 3
3 -1
输出是 3,但应该是 4

也许有人可以看到错误。我也愿意接受全新的想法来实施它。

【问题讨论】:

    标签: c# java sum max submatrix


    【解决方案1】:

    您刚刚忘记将下一个 rigth 元素添加到临时数组中:

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

    现在一切都很好! ;)

    问候

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 1970-01-01
      • 2012-12-03
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      相关资源
      最近更新 更多