数据结构与算法课程练习01-最大子序列和问题

01最大子序列和问题

      给定K个整数组成的序列{ N1, N2, ..., NK },“连续子列”被定义为{ Ni, Ni+1, ..., Nj },其中 1 <= i <= j <= K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。

输入格式:

输入第1行给出正整数 K (<= 100000);第2行给出K个整数,其间以空格分隔。

输出格式:

在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。

输入样例:
6

-2 11 -4 13 -5 -2

输出样例:
20
 1 #include<stdio.h>

 2 int main()

 3 {

 4   int k = 0,sum=0,flag1=0,count=0;

 5   int i,element,temp1,temp2,temp3;

 6   scanf("%d",&k);

 7   if(k<0){printf("error!");return 0;}

 8   int arr[k];

 9   for( i=0;i<k;i++)

10        {

11            scanf("%d",&element);

12            arr[i]=element;

13            if(arr[i]>0&&flag1==0)

14                {

15                   flag1=1;

16                   temp2=i;

17                }

18            if(arr[i]<=0)

19                {

20                  count+=1;

21                }

22            else if(arr[i]>0)

23                {

24                   temp3=i+1;

25                }

26         }

27   if(count==k)

28       {

29           printf("0\n");

30           return 0;

31       }

32   temp1=arr[temp2];

33   for( temp2;temp2<temp3;temp2++)

34         {

35             sum=arr[temp2];

36             for(i=temp2+1;i<temp3;i++)

37                 {

38                     temp1=((sum=sum+arr[i])>temp1)?sum:temp1;

39                 }

40         }

41   printf("%d\n",temp1);

42   return 0;
View Code

 

 

你可能感兴趣的:(数据结构与算法)