给定K个整数组成的序列{ N1, N2, ..., NK },“连续子列”被定义为{ Ni, Ni+1, ..., Nj },其中 1 <= i <= j <= K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。
输入格式:
输入第1行给出正整数 K (<= 100000);第2行给出K个整数,其间以空格分隔。
输出格式:
在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。
输入样例:6 -2 11 -4 13 -5 -2输出样例:
20
开始在云课堂学习数据结构了,然后,慢慢做题啦。
http://mooc.study.163.com/learn/ZJU-1000033001#/learn/custom?id=1000052001
这个题目的主要点是DP问题,如何解决的讲解在视频的第一节里面。
代码如下。
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int K;
int a[100000];
scanf("%d",&K);
for(int i=0; i<K; i++)
{
scanf("%d", &a[i]);
}
int res=0;
int max=0;
for(int i=0; i<K; i++)
{
max+=a[i];
res=(max>res?max:res);
if(max<0)
{
max=0;
}
}
printf("%d\n",res);
return 0;
}