Maximum Subsequence Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39579290/article/details/84833461

版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/qq_39579290/article/details/84833461

一:题目要求

Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A continuous subsequence is defined to be { N​i​​, N​i+1​​, ..., N​j​​ } where 1≤i≤j≤K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:

10
-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4

二:代码实现

#include<stdio.h>
#include<stdlib.h>
int main(){
	int n;
	int *a;
	scanf("%d",&n);
	a=(int*)malloc(n*sizeof(int));
	/* 
	sum:求当前子列和;
	max:最大子列和;
	begin,end:最大子列和的首位和末尾的下标; 
	flag:当前求和子列的第一个位置
	*/ 
	int i,sum=0,max=-1,begin=0,end=0,flag=0;
	//num是为了判断全是负数的情况 
	int num=0;
	for(i=0;i<n;i++){
		scanf("%d",&a[i]);
		sum+=a[i];//求和  
		if(sum<0){
			sum=0;
			flag=i+1;//如果sum<0,重置flag 
			num+=1;
		}
		else if(sum>max){
			max=sum;
			begin=flag;
			end=i;
		}
		
	}
	//如果全是负数,begin和max值不符合,需要重新判断 
	if(num==n){
		begin=0;
		end=n-1;
		max=0;
	}
	printf("%d %d %d",max,a[begin],a[end]);
	return 0;
} 

三:总结

1.此题对于有正有负的情况比较好判断,但是需要注意几种情况:一是对于全是负数的情况,此时最大值输出的是0,而最大子列输出的是第一个和最后一个元素;二是最大值是0的情况,需要根据最大值的初始值进行编码;三是对于最大值的序列有多种的情况,题目要求输出最先找到的序列。

2.时间复杂度:O(n)。

猜你喜欢

转载自blog.csdn.net/qq_39579290/article/details/84833461