Maximum sum
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 39089 | Accepted: 12221 |
Description
Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
Your task is to calculate d(A).
Input
The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, ..., an. (|ai| <= 10000).There is an empty line after each case.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, ..., an. (|ai| <= 10000).There is an empty line after each case.
Output
Print exactly one line for each test case. The line should contain the integer d(A).
Sample Input
1 10 1 -1 2 2 3 -3 4 -4 5 -5
Sample Output
13
Hint
In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.
Huge input,scanf is recommended.
Huge input,scanf is recommended.
分别求出两端开始的最大子段和,然后枚举左右两段的分界,找出最大值。
1 //2016.8.21 2 #include<iostream> 3 #include<cstdio> 4 #include<cstring> 5 6 using namespace std; 7 8 const int N = 50005; 9 const int inf = 0x3f3f3f3f; 10 int a[N], dpl[N], dpr[N];//dpl[i]表示从左往右到第i位的最大子段和,dpr[i]表示从右往左到第i位的最大子段和 11 12 int main() 13 { 14 int T, n; 15 cin>>T; 16 while(T--) 17 { 18 scanf("%d", &n); 19 for(int i = 0; i < n; i++) 20 { 21 scanf("%d", &a[i]); 22 } 23 memset(dpl, 0, sizeof(dpl)); 24 memset(dpr, 0, sizeof(dpr)); 25 //从左往右扫 26 //************************************************* 27 dpl[0] = a[0]; 28 for(int i = 1; i < n; i++) 29 if(dpl[i-1]>0) dpl[i] = dpl[i-1]+a[i]; 30 else dpl[i] = a[i]; 31 for(int i = 1; i < n; i++) 32 if(dpl[i]<dpl[i-1]) 33 dpl[i] = dpl[i-1]; 34 //从右往左扫 35 //************************************************* 36 dpr[n-1] = a[n-1]; 37 for(int i = n-2; i>=0; i--) 38 if(dpr[i+1]>0) dpr[i] = dpr[i+1]+a[i]; 39 else dpr[i] = a[i]; 40 for(int i = n-2; i>=0; i--) 41 if(dpr[i]<dpr[i+1]) 42 dpr[i] = dpr[i+1]; 43 //************************************************* 44 int ans = -inf; 45 for(int i = 0; i < n-1; i++) 46 { 47 ans = max(ans, dpl[i]+dpr[i+1]); 48 } 49 cout<<ans<<endl; 50 } 51 52 return 0; 53 }