Problem Links:
poj2479,
Problem:
Maximum sum
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 20936 | Accepted: 6347 |
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.
Source
POJ Contest,Author:Mathematica@ZSU
Solution:
Source Code:
#include <stdio.h>int main()
{
freopen("input.in", "r", stdin);
freopen("output.out", "w", stdout);
int t, n, i, max, sum;
int a[50000], b[50000], c[50000];
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
max = 0;
sum = 0;
if (n == 1)
{
scanf("%d", &a[0]);
printf("%d\n", a[0]);
continue;
}
if (n == 2)
{
scanf("%d", &a[0]);
scanf("%d", &a[1]);
printf("%d\n", a[0] + a[1]);
continue;
}
//b[i] is the max sum from 0 to i.
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
sum += a[i];
if (sum < 0)
sum = 0;
else if (sum > max)
max = sum;
b[i] = max;
}
//c[i] is the max sum from i to the end.
max = 0;
sum = 0;
for (i = n - 1; i >= 0; i--)
{
sum += a[i];
if (sum < 0)
sum = 0;
else if (sum > max)
max = sum;
c[i] = max;
}
max = 0;
for (i = 0; i < n - 1; i++)
if (b[i] + c[i + 1] > max)
max = b[i] + c[i + 1];
printf("%d\n", max);
}
return (0);
}
No comments :
Post a Comment