编程珠玑(第八章习题13)

习题13. 在最大子数组问题中,给定m*n的实数数组,我们需要求出矩形子数组的最大总和。该问题的复杂度如何?

 问题解析:可以在长度为m的维度上使用算法2,而在长度为n的维度上使用算法4。可以在O(m^2*n)的时间复杂度内解决m*n问题。 

 算法 c程序源码:

复制代码
 1 float max_subarr(float **array, int row, int col)
 2 {
 3     int i, j, k;
 4     float *vector, max = 0, maxsofar, maxendinghere;
 5     assert(row > 0 && col > 0);
 6     vector = (float *) malloc(col * sizeof(float));
 7     assert(vector != NULL);
 8     printf("the array :\n");
 9     for( i = 0; i < row; i ++)
10     {
11         memset(vector, 0, col * sizeof(float));//初始化为0
12         for( j = i; j < row; j ++)
13         {
          //vector[k]的值为行i至行j的第k列元素之和,把二维问题转化为一维问题。 
14 for(k = 0; k < col; k ++) 15 vector[k] += array[j][k];//vector[k] = array[i][k] + array[i + 1][k] + ... + array[j][k],
16 maxsofar = vector[0]; 17 maxendinghere = 0; 18 for(k = 0; k < col; k ++) 19 { 20 maxendinghere = (maxendinghere + vector[k]) > 0 ? (maxendinghere + vector[k]) : 0; 21 maxsofar = maxsofar > maxendinghere ? maxsofar : maxendinghere; 22 } 23 24 max = max > maxsofar ? max : maxsofar; 25 26 } 27 } 28 return max; 29 }
复制代码
posted @ 2013-04-18 09:25  busyfruit  阅读(259)  评论(0)    收藏  举报