我正在尝试从给定的nxn矩阵中获取最大子矩阵和。从我读到的算法来看,算法的复杂度为n ^ 3(kadane)。我尝试使用我在stackoverflow上找到的代码在java中实现它(由Anders Gustafsson在C#in these post中编写),但它似乎并不总是有效。
我的代码是:
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;
}
我有三个例子:
Matrix 1
-2 -3
-1 -4
输出为0(空0x0矩阵也是一个解决方案)
Matrix 2
2 -1
-2 -1
输出为2
Matrix 3
-1 3
3 -1
输出为3,但应为4
也许有人可以看到错误。我也愿意接受全新的想法来实现它。
答案 0 :(得分:0)
您刚忘记将下一个rigth元素添加到temp-array:
(int i=0; i<row; i++)
tempArray[i] += matrix[i][right];
现在一切都很好! ;)
格尔茨