二维数组

            dp = arr[i];
27         else
28             dp += arr[i];
29         if (dp < min)
30             min = dp;
31         sum += arr[i];
32     }
33     max2 = sum - min;//数组全部元素和减去最小子数组
34     return max1>max2 ? max1 : max2;//三目运算符;如果max1>max2,将max1的值返回,否则返回max2
35 }
36 int maxSubMatrix(int n, int m, int array[M][N])
37 {
38     int i, j, h, max, sum = -100000;
39     int b[100];
40     for (i = 0; i<n; i++)
41     {
42         memset(b, 0, sizeof(b));       //初始化b[] 
43         for (j = i; j<n; j++)          //把第i行到第j行相加,对每一次相加求出最大值 
44         {
45             for (h = 0; h<m; h++)
46             {
47                 b[h] += array[j][h];   //二维数组压缩成一维数组,然后求最大子序列和 
48             }
49             max = maxSubArray(b, h);
50
51             if (max>sum)
52                 sum = max;
53         }
54     }
55     return sum;
56 }
57 int main()
58 {
59     int arr[M][N];
60     cout << "随机二维数组为:" << endl;
61     srand(time(0));
62     for (int i = 0; i < M; i++)
63     {
64         for (int j = 0; j < N; j++)
65         {
66             arr[i][j] = rand() % 50 - 25;
67             cout << arr[i][j] << " ";
68         }
69         cout << endl;
70     }
71     cout <<"最大子数组的和:"<< maxSubMatrix(M, N, arr) << endl;
72     return 0;
73     }

将二位数组压成一个一位数组,然后利用一位数组求最大字数组方式求

posted @ 2015-04-24 09:46  马思勉  阅读(108)  评论(0编辑  收藏  举报