hdu1003 Max Sum
水题一枚,开始写出了一个复杂度n平方的代码,提交 果然tle,
然后观察数据 再优化了一些具体情况,还是tle,
这样的优化还是治标不治本啊,,
后来按捺不住我又看了别人的代码,,原来可以把复杂度弄成o(n);
只需要遍历1次即可。
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 158459 Accepted Submission(s): 37061
Problem Description
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence.
If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Sample Output
Case 1: 14 1 4 Case 2: 7 1 6
#include <iostream> #include <cstring> #include <cstdio> #define maxn 100010 using namespace std; int num[maxn]; int main() { int t; int cnt=0; cin>>t; while(t--) { memset(num,0,sizeof(num)); int n; cin>>n; for(int i=1;i<=n;i++) cin>>num[i]; __int64 sum=0; int start=1;__int64 max=(-1)*maxn*1000;//因为可能都是负数,所以设置初始max尽可能的小
int st=1;int end=1;//初始化 for(int i=1;i<=n;i++) { if(sum>=0) sum+=num[i];//如果之前的和大于等于0,继续加 else { sum=num[i];//否则,舍弃前面所有的数据,从这一项开始 st=i;//记录起始点 } if(sum>max) { start=st; max=sum; end=i; } } if(cnt>0) cout<<endl; cout<<"Case "<<++cnt<<':'<<endl; cout<<max<<' '<<start<<' '<<end<<endl; } return 0; }