最大连续子序列之和

  给定序列:-2, 11, -4, 13, -5, -2

  和最大连续子序列: 11, -4, 13 

  array[i]:给定序列

  d[i]: 以i为起点的最大连续序列和

  m[i]: 以i为起点的最大连续序列和的结束位置

实现如下:

 1 int GetMaxSum(int n)
 2 {
 3     int nBegPos = 0;
 4     int nSum;
 5     int nEndPos = 0;
 6     int i, j;
 7     for(i=0; i<n; ++i)
 8     {
 9         nSum = d[i] = array[i];
10         m[i] = i;
11         for(j=i+1; j<n; ++j)
12         {
13             nSum += array[j];
14             if(nSum > d[i])
15             {
16                 d[i] = nSum;
17                 m[i] = j;
18             }
19         }
20     }
21     nSum = 0;
22     for(i=0; i<n; ++i)
23     {
24         if(nSum < d[i])
25         {
26             nSum = d[i];
27             nBegPos = i;
28             nEndPos = m[i];
29         }
30     }
31     printf("%d\n", nSum);
32     for(i=nBegPos; i<=nEndPos && nBegPos!=nEndPos; ++i)
33     {
34         printf("%d ", array[i]);
35     }
36     printf("\n");
37     return 0;
38 }

  空间优化后的程序:

 1 int GetMaxSum2(int n)
 2 {
 3     int nMax;
 4     int nBegPos = 0;
 5     int nSum;
 6     int nEndPos = 0;
 7     int i, j;
 8     nMax = 0;
 9     for(i=0; i<n; ++i)
10     {
11         nSum = array[i];
12         for(j=i+1; j<n; ++j)
13         {
14             nSum += array[j];
15             if(nSum > nMax)
16             {
17                 nMax = nSum;
18                 nBegPos = i;
19                 nEndPos = j;
20             }
21         }
22     }
23     printf("%d\n", nMax);
24     for(i=nBegPos; i<=nEndPos && nBegPos!=nEndPos; ++i)
25     {
26         printf("%d ", array[i]);
27     }
28     printf("\n");
29     return 0;
30 }

  时间优化后的程序:

 1 int GetMaxSum3(int n)
 2 {
 3     int nMax;
 4     int nBegPos = 0;
 5     int nSum;
 6     int nEndPos = 0;
 7     int i, j;
 8     nMax = 0;
 9     for(i=0, j=0; j<n; ++j)
10     {        
11         nSum += array[j];
12         if(nSum > nMax)
13         {
14             nMax = nSum;
15             nBegPos = i;
16             nEndPos = j;
17         }
18         else if(nSum < 0)
19         {
20             i = j + 1;
21             nSum = 0;
22         }
23     }
24     printf("%d\n", nMax);
25     for(i=nBegPos; i<=nEndPos && nBegPos!=nEndPos; ++i)
26     {
27         printf("%d ", array[i]);
28     }
29     printf("\n");
30     return 0;
31 }

  第三版程序中,当发现nSum小于0时,直接将i移动到j+1作为新的起点。据说这是连续序列和的一个特性,本人琢磨了半天也没理解上去。。。

主函数程序:

int main()
{
    int i=0;
    int nLastNum = -1;
    int nArrayLen;
    scanf("%d", &nArrayLen);
    i=0;
    while(i < nArrayLen)
    {
        scanf("%d", &array[i]);
        ++i;
    }
    while(i<5001)
    {
        ++i;
    }
    GetMaxSum(nArrayLen);
    GetMaxSum2(nArrayLen);
    GetMaxSum3(nArrayLen);
    return 0;
}

posted on 2012-08-30 16:40  favourmeng  阅读(222)  评论(0编辑  收藏  举报

导航