寻找和最大的连续子串

(原创文章,转载请注明出处!)

给定一组数,n个,有正,有负。要求找到和最大的连续子串,比如:

5 , 4, -10, 11, 2, 8, -5, 4, 2,-3,1

可以判断出和最大的连续子串是: 11, 2, 8, -5, 4, 2   ,   其和为22 。

算法思路:(来自于《编程珠玑》)

假设已经找出了从0到i-1中的最大子串,现在要处理加入元素i后的情况,

有两种可能:最大子串还是0到i-1中的那个最大子串,记为Maxpre;最大子串要包含元素i,记为Maxcur

比较Maxpre与Maxcur 将大的赋值给Maxpre ,继续往前扫描,直到处理完最后一个元素,由此形成一个O(n)的算法。

获得Maxcur的方法:第一种、 每次直接从当前的ith元素往前扫描,找到包含ith元素的最大子串。

                         第二种、记住包含i-1th元素的最大子串,然后直接加上ith元素即可

代码实现如下:

 1 #include <stdlib.h>
 2 
 3 typedef struct subIdx {
 4     int begin;
 5     int end;
 6 } SUB_IDX;
 7 
 8 typedef struct maxSub {
 9     SUB_IDX subPosition;
10     int sum;
11 } MAX_SUB;
12 
13 MAX_SUB * MaxSubScan(const int* array, int len)
14 {
15     SUB_IDX MaxPreIdx;
16              MaxPreIdx.begin = 0;
17              MaxPreIdx.end = 0;
18     SUB_IDX MaxCurIdx;
19              MaxCurIdx.begin = 0;
20              MaxCurIdx.end = 0;
21     int MaxPre = 0;
22     int MaxCur = 0;
23     
24     for (unsigned int i = 0 ; i < len; i++) {
25         if ((MaxCur + array[i]) > 0) {
26             MaxCur = MaxCur + array[i];
27             MaxCurIdx.end = i;
28         } else {
29             MaxCur = 0;
30             MaxCurIdx.begin = i + 1;
31             MaxCurIdx.end = i + 1;
32         }
33 
34         if (MaxCur > MaxPre) {
35             MaxPre = MaxCur;
36             MaxPreIdx.begin = MaxCurIdx.begin;
37             MaxPreIdx.end = MaxCurIdx.end;
38         }
39     }
40 
41     MAX_SUB *maxsub = (MAX_SUB *) malloc( sizeof(MAX_SUB) );
42     maxsub->subPosition.begin = MaxPreIdx.begin;
43     maxsub->subPosition.end = MaxPreIdx.end;
44     maxsub->sum = MaxPre;
45 
46     return maxsub;
47 }

 

posted @ 2014-11-11 23:29  activeshj  阅读(396)  评论(0)    收藏  举报