key point
scan the array by order
nowsum saves the current answer
maxsum always saving the max value
and when nowsum is minus ,drop it ,
cause a minus only reduces the following value
#include <stdio.h>#include <stdlib.h>int online (intlist[],int N){//list,length of list=N
int nowsum=0,maxsum=0,i=0;while(i<=N-1){
nowsum+=list[i];if(nowsum<0) nowsum=0;//drop the minus
elseif(nowsum>maxsum) maxsum=nowsum;//maxsum always saving the max
i++;}return maxsum ;}int main(){int N,i,result;
printf("please input the length of list :\n");
scanf("%d",&N);int*l;//dynamic array
l=(int*)malloc(sizeof(int)*N);if(l){
printf("input numbers divided by space:\n");for(i=0;i<N;i++) scanf("%d",l+i);
printf("\n");
printf("your list is :\n");for(i=0;i<N;i++) printf("%d\t",l[i]);
printf("\n");}else printf("error!");
result =online(l,N);
printf("\nthe result is %d",result);
free(l);
l=NULL;}
result
please input the length of list :
8
input numbers divided by space:
4 -3 5 -2 -1 2 6 -2
your list is :
4 -3 5 -2 -1 2 6 -2
the result is 11