最长子序列

时间复杂度为N方

 1 #include <iostream>
 2 
 3 using namespace std;
 4 //最长子序列
 5 
 6 int MaxSequence(int a[],int N)
 7 {
 8     int thisSum,maxSum=0,i,j;
 9     for(i=0;i<N;i++)
10     {
11         thisSum=0;
12         for(j=i;j<N;j++)
13         {
14             thisSum+=a[j];
15             if(thisSum>maxSum)
16                 maxSum=thisSum;
17         }
18     }
19     return maxSum;
20 };
21 
22 
23 int main()
24 {
25     int a[10]={2,-1,13,-5,7,8,-65,12,8,-2};
26     cout<<MaxSequence(a,10);
27     return 0;
28 }

 时间复杂度为N

 1 #include <iostream>
 2 
 3 using namespace std;
 4 //最长子序列
 5 
 6 int MaxSequence(int a[],int N)
 7 {
 8     int thisSum,maxSum,j;
 9     thisSum=maxSum=0;
10     for(j=0;j<N;j++)
11     {
12         thisSum+=a[j];
13         if(thisSum>maxSum)
14             maxSum=thisSum;
15             else if(thisSum<0)//这里是关键  
16                 thisSum=0;
17         cout<<maxSum<<endl;
18     }
19     return maxSum;
20 };
21 
22 
23 int main()
24 {
25     int a[10]={-1,-1,13,-5,7,8,-65,12,8,-2};
26     cout<<MaxSequence(a,10);
27     return 0;
28 }

 

posted @ 2013-04-07 19:55  天晴会下雨  阅读(476)  评论(0编辑  收藏  举报