Circular Sequence

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 el
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/* 题意: N个数围成一个环,求截取一段子序列,使截取的子序列,是所有子序列中的和中是最大的。
解题报告:求整个数列的 最大和(maxsum) 和 最小和(minsum),判断maxsum与sum(整个数列的和) - minsum,
如果最大和大则输出maxsum,否则输出sum - minsum(即所求序列是最后一个数能与第一个数相连的子串).
例如:1, -2, 3, -4, 2, 4, 6; sum = 10, maxsum = 12, minsum = -4;
*/
//标程:
#include<iostream>
#include<cstdio>
using namespace std;
const int inf = (1 << 31) - 1;
int main()
{
//	freopen("a.txt","r",stdin);
    int n, i, t, x;
	cin >> t;
	while(t --)
	{
		cin >> n;
		__int64 max = -inf, min = inf, s(0), maxsum(0), minsum(0);
		int flag(0);
		for(i = 1; i <= n; i ++)
		{
			scanf("%d",&x);
			if(x >= 0) flag = 1;
            s += x;
            maxsum += x;
			minsum += x;
			if(maxsum > max)  max = maxsum;  
			if(maxsum < 0) maxsum = 0;
			if(minsum < min) min = minsum;
			if(minsum > 0) minsum = 0;
		}
		if(flag == 0) 
			 printf("%I64d\n",max);
		else
		   printf("%I64d\n",(max > s - min ? max : s - min));
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值