给定KK个整数组成的序列{ N_1N1, N_2N2, ..., N_KNK },“连续子列”被定义为{ N_iNi, N_{i+1}Ni+1, ..., N_jNj },其中 1 \le i \le j \le K1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。
本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:
数据1:与样例等价,测试基本正确性;数据2:102个随机整数;数据3:103个随机整数;数据4:104个随机整数;数据5:105个随机整数;输入第1行给出正整数KK (\le 100000≤100000);第2行给出KK个整数,其间以空格分隔。
在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。
解题思路:对于全为负数的特判一下,否则就遍历一遍所有数,若到当前数时和小于零,和清为零,在遍历时不断更新最大值
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <algorithm> #include <cmath> #include <queue> #include <vector> #include <set> #include <stack> #include <map> #include <climits> #include <functional> using namespace std; #define LL long long const int INF=0x3f3f3f3f; int a[100009]; int main() { int n; while(~scanf("%d",&n)) { int flag=0; for(int i=1;i<=n;i++) { scanf("%d",&a[i]); if(a[i]>=0) flag=1; } if(!flag) {printf("0\n");continue;} int ma=-INF,sum=0; for(int i=1;i<=n;i++) { if(sum+a[i]<0) sum=0; else { sum+=a[i]; ma=max(sum,ma); } } printf("%d\n",ma); } return 0; }