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 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值