学习得到的代码
#include<iostream>
5 #include<stdlib.h>
6 #include <time.h>
7 using namespace std;
8 struct ret
9 {
10 int max, start, end; //用于存放最大值,及始末位置
11 };
12
13 struct ret max2(int arry[], int length) //跨越arry[n-1]、arry[0]的最大和
14 {
15 int total = 0;
16 int start1 = 0;
17 int start2; //起始位置
18 int end = 0;
19 int sum = arry[0];
20 int minsum = arry[0];
21 for (int i = 1; i<length; i++)
22 {
23 if (sum>0)
24 {
25 sum = arry[i];
26 start1 = i;
27 }
28 else
29 {
30 sum = sum + arry[i];
31
32 }
33 if (minsum >= sum)
34 {
35 minsum = sum;
36 end = i;
37 start2 = start1;
38 }
39 total = total + arry[i];
40 }
41 total = total + arry[0];
42 minsum = total - minsum;
43 struct ret ret1 = { minsum, start2, end };
44 return ret1;
45 }
46
47 struct ret max1(int arry[], int length) //不跨越零点的最大和
48 {
49 int start1 = 0;
50 int start2; //起始位置
51 int end = 0;
52 int sum = arry[0];
53 int maxsum = arry[0];
54 for (int i = 1; i<length; i++) //求出相邻数组最小和
55 {
56 if (sum<0)
57 {
58 sum = arry[i];
59 start1 = i;
60 }
61 else
62 {
63 sum = sum + arry[i];
64 }
65 if (maxsum <= sum)
66 {
67 start2 = start1;
68 end = i;
69 maxsum = sum;
70 }
71 }
72 struct ret ret1 = { maxsum, start2, end };
73 return ret1;
74 }
75
76 int main()
77 {
78 srand((unsigned)time(0));
79 int N;
80 cout << "输入元素个数:";
81 cin >> N;
82 int a[20];
83 for (int i = 0; i<N; i++)
84 {
85 a[i] = rand() % 20 - 10;
86 cout << a[i] << " ";
87 }
88 cout << endl;
89 struct ret w = max2(a, N); //调用max2函数,求跨越零点的最值
90 struct ret q = max1(a, N);
91 if (w.max>q.max)
92 {
93 cout << "最大和为:" << w.max << "\n起始位置:" << w.end + 1 << "\n结束位置:" << w.start - 1 << endl;
94 }
95 else
96 {
97 cout << "最大和为:" << q.max << "\n起始位置:" << q.start << "\n结束位置:" << q.end << endl;
98 }
99 return 0;