Max Sum
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 6 Accepted Submission(s) : 4
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
There are N intergers make up a loop. Your job is to calculate the max sum of consecutive sub-suquence in the loop. Note, you can select a null consecutive sub-suquence.
For example, given (3, 1, -5, 2), the max sum is 2+3+1 = 6.
Input
The first line of the input contains an integer T (1<=T<=50) which means the number of est cases. Then T lines follow, and each line starts with a number N (1<=N<=100,000), then N integers followed (all the integers are between -1,000 and 1,000).
Output
For each test case, you should output one integers, the max sum.
Sample Input
3
4
3 1 -5 2
2
-4 -1
5
3 -1 4 -4 -2
Sample Output
6
0
6
题意:在一个环序列中,找出最大连续序列和 思路:求最大连续序列和 ,有两种情况:总和-最小连续序列和,或者是,最长连续序列和; 代码:#include <cstdio> #include <iostream> #include <cstring> #include <vector> #include <algorithm> using namespace std; #define max(a ,b) a>b?a:b #define min(a ,b) a<b?a:b #define INF 1000005 #define PI atan(1.0)*4.0 #define N 1000005 int a[N]; int main() { freopen("in.txt" ,"r" ,stdin); freopen("out.txt" ,"w" ,stdout); int t; scanf("%d" ,&t); while(t--) { int n; scanf("%d" ,&n); int sum = 0; for(int i = 0 ; i < n ; i++) { scanf("%d" ,&a[i]); sum += a[i]; } int sump = 0 , max = 0 ,res = 0; for(int i = 0; i < n ; i++) { sump += a[i]; if(sump > 0) sump = 0; max = sump < max ? sump : max; } sum -= max; sump = 0; for(int i = 0 ; i < n ; i++) { sump += a[i]; if(sump < 0) sump = 0; res = sump > res ? sump : res; } res = res > sum ? res:sum; printf("%d\n" ,res); } return 0; }