经典DP之最大子矩阵和问题

转载请注明作者与出处:franciscolv http://www.cnblogs.com/franciscolv/archive/2011/11/20/2255849.html

package SortSet;

/**
*
*
@author franciscolv
* 假设从第i行到第j行,第m列到第n列使得该矩阵元素和最大。
* 则和为i行,m到n列和 +。。。。+j行 m到n列和,
* 则可转化为数组中元素连续和最大问题
*/
public class MaxSubMatrix {
public static void main(String[] args) {
int[][] a = { { 0, -2, -7, 0 },
{ 9, 2, -6, 2 },
{ -4, 1, -4, 1 },
{ -1, 8, 0, -2 } };
System.out.println(getMaxSumForSubMatrix(a));
}

/**
*
* o(n*n)个问题,每个问题都是求连续最大和 O(n)可解,
* 故为o(n^3)时间复杂度
* o(n)空间复杂度
*
@param a
*
@return
*/
public static int getMaxSumForSubMatrix(int[][] a) {
int n = a.length;
int[] max = new int[n];
int i, j, k, result = 0;
int sum = Integer.MIN_VALUE;
for (i = 0; i < n; i++) {
for (k = 0; k < n; k++)
max[k] = 0;
for (j = i; j < n; j++) {
for (k = 0; k < n; k++)
max[k] += a[j][k];

result = getMaxSum(max);
// 0 9 6 13 11 8 15 1 9 8
System.out.print(result + " ");
if (result > sum)
sum = result;
}
}
System.out.println();
return sum;
}

private static int getMaxSum(int[] a) {
int max = Integer.MIN_VALUE;
int result = 0;
for (int i = 0; i < a.length; i++) {
if (result > 0)
result += a[i];
else
result = a[i];
if (result > max)
max = result;
}
return max;
}
}



  

posted @ 2011-11-20 11:10  franciscolv  阅读(373)  评论(0编辑  收藏  举报