Given n integers (possibly negative) a1,a2,... an. ai,ai+1,... aj where I < = I < = J < = n is the maximum value of the sum of the subsegments. When all integers are negative, we define the sum of their largest subsegments as 0, and the initial and end positions as 0. For example, when (a1,a2,a3,a4,a5,a6) = (- 2,11, - 4,13, - 5, - 2), the problem that the sum of the largest subsegments is a2+a3+a4=20, i=2,j=4 (subscript starts from 1) is called the "maximum subsegment and problem".
In exam one, we assume n < = 200. Today, we change the scope of n to n < = 2000. Your task is to design a program to solve it.
Input
The input consists of two lines, the first line is n; the second line is n integers.
Output
The output also has two lines. The first line is "From=xxx,To=xxx"; the second line is "MaxSum=xxxx". See the example.
Sample Input
6 -2 11 -4 13 -5 -2
Sample Output
From=2,To=4 MaxSum=20
#include<bits/stdc++.h> using namespace std; const int MAXN=100005; int n; long long a[MAXN],sum,ansum; pair<int,int>ans; int main() { while(scanf("%d",&n)!=EOF) { for(int i=1;i<=n;++i) { scanf("%lld",&a[i]); } bool flag=false; for(int i=1;i<=n;++i) { if(a[i]>=0)flag=true; } if(!flag) { printf("From=0,To=0\nMaxSum=0\n"); continue; } int pos=0; ansum=-1; sum=0; for(int i=1;i<=n;++i) { sum+=a[i]; if(sum<0) { sum=0; pos=i; } else { if(sum>ansum) { ansum=sum; ans=make_pair(pos+1,i); } else if(sum==ansum) { ans=min(ans,make_pair(pos+1,i)); } } } printf("From=%d,To=%d\nMaxSum=%lld\n",ans.first,ans.second,ansum); } return 0; }