Problem Description
Given a sequence with n elements, if the last element is also adjacent to the first element of the sequence, the sequence is called “circular sequence”.
Now, here comes a simple problem: given a circular sequence, you should find a segment of the sequence, such that it contains at least one element, and the sum of the elements is as large as possible.
Input
Input may contain several test cases. The first line is a single integer t, the number of test cases below. Each test case is composed of two lines. The first line of each test case is a positive integer n (1<=n<=100000), denoting the number of elements in the circular sequence, and the second line has n integers; the absolute value of each integer is no more than 100000.
Output
For each test case, output the maximum segment sum in a single line.
Sample Input
2
2
-1 -2
3
1 -2 3
Sample Output
-1
Given a sequence with n elements, if the last element is also adjacent to the first element of the sequence, the sequence is called “circular sequence”.
Now, here comes a simple problem: given a circular sequence, you should find a segment of the sequence, such that it contains at least one element, and the sum of the elements is as large as possible.
Input
Input may contain several test cases. The first line is a single integer t, the number of test cases below. Each test case is composed of two lines. The first line of each test case is a positive integer n (1<=n<=100000), denoting the number of elements in the circular sequence, and the second line has n integers; the absolute value of each integer is no more than 100000.
Output
For each test case, output the maximum segment sum in a single line.
Sample Input
2
2
-1 -2
3
1 -2 3
Sample Output
-1
4
#include <iostream>
#include <stdio.h>
#define INF 0xfffffff
using namespace std;
int main()
{
//freopen("b.txt","r",stdin);
int cases,n,i,x;
bool flag;
__int64 s, max, min, sum_max, sum_min;
scanf("%d", &cases);
while (cases--)
{
scanf("%d",&n);
s = 0;
sum_max = 0;
sum_min = 0;
max =-INF;
min =INF;
flag = true;
for (i = 0; i < n; i ++)
{
scanf("%d", &x);
if (x >= 0)
flag = false;
s += x;
sum_max += x;
sum_min +=x;
if (sum_max > max)
max = sum_max;
if (sum_max < 0)
sum_max = 0;
if (sum_min < min)
min = sum_min;
if (sum_min > 0)
sum_min = 0;
}
if(!flag)
printf("%I64d\n", max > s - min ? max : s - min);
else
printf("%I64d\n", max);
}
return 0;
}