bit 1010 Maximum Sum

本文介绍了一个经典的编程问题——最大子段和问题,并提供了一种有效的解决方案。该问题要求从一组整数中找到连续子序列的最大和。通过线性扫描的方法,能够在O(n)的时间复杂度内解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Maximum Sum

时间限制: 2秒  内存限制: 64M

Problem Description

Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:

d(A) = max(sum(a[i] +a[i+1] + … + a[j])) ( 1 <= i <= j <= n).

Now your task is to calculate d(A).

Input

The input consists of T(T<=30) test cases. The number of testcases (T) is given in the first line of the input. 
Each test case contains two lines. The first line is an integer n(1<=n<=50000). The second line contains n integers: a1, a2, ..., an. (|ai| <= 10000).

Output

Print exactly one line for each test case. The line should containthe integer d(A).

Sample Input

1

10

1 -1 2 2 3 -3 4 -4 5 -5

Sample Output

9

菜鸟一个,不会做,参考一下大神blog线性干掉。嘿嘿

#include<stdio.h>
int main(){

	int testCase,input_num;
	int a[50010],max,sum;
	//FILE *fp;
	//fp = freopen("in.txt","r",stdin);
	scanf("%d",&testCase);
	while(testCase--){
		scanf("%d",&input_num);
		scanf("%d",&a[0]);
		max = a[0];
		for(int i = 1; i <  input_num; ++i){
			scanf("%d",&a[i]);
			if(max < a[i]){
				max = a[i];
			}
		}
		
		if(max <= 0){
			printf("%d\n",max);
		}else{
			sum = 0;
			for(int i = 0; i < input_num;++i){
				sum	+= a[i];
				if(sum < 0){
					sum = 0;
				}
				if(sum > max){
					max = sum;
				}
			} 
			printf("%d\n",max);
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值