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 }
将二位數組壓成一個一位數組,然後利用一位數組求最大字數組方式求