- 论坛徽章:
- 0
|
求一个数组中最大的相邻元素之和
阅读了yuxh的算法,改造了一下,使逻辑统一一下:
各位验证一下
- #include <stdio.h>;
- void MaxSum(int *ary, int n)
- {
- int i, start=0, end=0, start1=0, max, sum;
- max=sum=ary[0];
-
- for(i=1; i<n; i++)
- {
- if(ary[i] >; 0 && sum <= 0)
- {
- start1 = i;
- }
-
- sum += ary[i];
-
- if(sum<0)
- {
- start1=i;
- }
- if (sum >; max)
- {
- start = start1;
- end = i;
- max = sum;
- }
- else if(sum < 0)
- {
- sum = 0;
- }
- }
- printf("start %d, end %d, sum %d\n", start, end, max);
- }
- void main()
- {
- int m[10] = {2, 3, -6, 3, 4, 3, -7, 5, 3, -3};
- MaxSum(m, 10);
-
- return;
- }
复制代码 |
|