Maximum Contiguous Mum I

Description

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

Input Description
The first line of the input contains an integer T(1<=T<=50) which means the number of test cases. Then T lines follow, 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 Description
For each test case, you should output one integers, the max contiguous sub-suquence sum.
Sample Input
3
4
3 1 -5 2
2
-4 -1
5
3 -1 4 -4 -2
Sample Output
6
0
6

 

分两种情况考虑,最长连续和,可能是总和-最小连续和,也可能是最长连续和

#include <iostream>
#include <cstdio>
using namespace std;
int A[200108];
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		int sum=0;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&A[i]);
			sum+=A[i];
		}
		int maxlen=0;
		int sum1=0;
		for(int i=1;i<=n;i++)
		{
			sum1+=A[i];
			if(sum1>0)
			{
				sum1=0;
			}
			if(sum1<maxlen)
			{
				maxlen=sum1;
			}
		}
		sum-=maxlen;
		sum1=0;
		int aa=0;
		for(int i=1;i<=n;i++)
		{
			sum1+=A[i];
			if(sum1<0)
			{
				sum1=0;
			}
			if(sum1>aa)
			{
				aa=sum1;
			}
		}
		sum=sum>aa?sum:aa;
		printf("%d\n",sum);
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值