最大序列和

题目描述

给出一个整数序列S,其中有N个数,定义其中一个非空连续子序列T中所有数的和为T的“序列和”。 对于S的所有非空连续子序列T,求最大的序列和。 变量条件:N为正整数,N≤1000000,结果序列和在范围(-2^63,2^63-1)以内。 
输入描述:
第一行为一个正整数N,第二行为N个整数,表示序列中的数。


输出描述:
输入可能包括多组数据,对于每一组输入数据,
仅输出一个数,表示最大序列和。

输入例子:
5
1 5 -3 2 4

6
1 -2 3 4 -10 6

4
-3 -1 -2 -5

输出例子
9
7
-1

比较好的算法就是动态规划,用一个数字记录每次累加的值,如果res的值小于0,前边的那一串数字都不会构成最大。所以将res的值赋值为数组的下个数。还需要有一个max变量来记录子串的最大值。代码如下:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
	int n,i,j;
	int temp;
	int res = 0,max=0;
	while (cin >> n)
	{
		res = 0;
        max=0;
		vector<int> num;
		for ( i = 0; i < n; i++)
		{
			cin >> temp;
			num.push_back(temp);
			
           if(i==0)
                max=temp;
          
			if (res > 0)
			      res += temp;
            else 
                res=temp;
            if(res>max)
                max=res;
		}
			cout << max << endl;
	}


}



猜你喜欢

转载自blog.csdn.net/weixin_36704535/article/details/53283839