算法 | 最大字段和

 

  

 

 

#include <stdio.h>
int a[100001],dp[100001];
int main()
{
    int T,n;
    while(~scanf("%d",&n))
    {
        
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        dp[0] = a[0];
        int start = 0,end = 0,max = -1001;
        int first = 0,last = 0;
        for(int i=0;i<n;i++)
        {
            if(dp[i-1]+a[i]>=a[i])         //判断条件
            {
                dp[i] = dp[i-1]+a[i];
                end = i;
            }
            else
            {
                dp[i] = a[i];
                start = end = i;
            }
            if(max<dp[i])
            {
                max = dp[i];
                first = start;
                last = end;
            }
        }
        if(max < 0) {
        	printf("0");
		}else {
			printf("%d",max);
        
	        for(int i = first; i <= last; i++) {
	        	printf(" %d",a[i]);
			} 	
		}
        
       
        printf("\n");
        
    }
    return 0;
}

  

posted @ 2018-11-07 23:27  听说这是最长的名字了  阅读(465)  评论(0编辑  收藏  举报