Max Sum

Max Sum

Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other)

Total Submission(s) : 6   Accepted Submission(s) : 4

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

Problem Description

There are N intergers make up a loop. Your job is to calculate the max sum of consecutive sub-suquence in the loop. Note, you can select a null consecutive sub-suquence.
For example, given (3, 1, -5, 2), the max sum is 2+3+1 = 6.

Input

The first line of the input contains an integer T (1<=T<=50) which means the number of est cases. Then T lines follow, and each line starts with a number N (1<=N<=100,000), then N integers followed (all the integers are between -1,000 and 1,000).

Output

For each test case, you should output one integers, the max sum.

Sample Input

3

4

3 1 -5 2

2

-4 -1

5

3 -1 4 -4 -2

 

Sample Output

6

0

6


题意:在一个环序列中,找出最大连续序列和
思路:求最大连续序列和 ,有两种情况:总和-最小连续序列和,或者是,最长连续序列和;
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define max(a ,b) a>b?a:b
#define min(a ,b) a<b?a:b
#define INF 1000005
#define PI atan(1.0)*4.0
#define N 1000005
int a[N];
int main()
{
    freopen("in.txt" ,"r" ,stdin);
    freopen("out.txt" ,"w" ,stdout);
    int t;
    scanf("%d" ,&t);
    while(t--)
    {
    	int n;
    	scanf("%d" ,&n);
    	int sum = 0;
    	for(int i = 0 ; i < n ; i++)
    	{
    		scanf("%d" ,&a[i]);
    		sum += a[i];
    	}
    	int sump = 0 , max = 0 ,res = 0;
    	for(int i = 0;  i < n ; i++)
    	{
    		sump += a[i];
    		if(sump > 0)
    			sump = 0;
    		max = sump < max ? sump : max;
    	}
    	sum -= max;
    	sump = 0;
    	for(int i = 0 ; i < n ; i++)
    	{
    		sump += a[i];
    		if(sump < 0)
    			sump = 0;
    		res = sump > res ? sump : res;
    	}
    	res = res > sum ? res:sum;
    	printf("%d\n" ,res);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值