洛谷1115 最大子段和
本题地址: http://www.luogu.org/problem/show?pid=1115
题目描述
给出一段序列,选出其中连续且非空的一段使得这段和最大。
输入输出格式
输入格式:
输入文件maxsum1.in的第一行是一个正整数N,表示了序列的长度。
第2行包含N个绝对值不大于10000的整数A[i],描述了这段序列。
输出格式:
输入文件maxsum1.out仅包括1个正整数,为最大的子段和是多少。
输入输出样例
输入样例#1:
7 2 -4 3 -1 2 -4 3
输出样例#1:
4
说明
【样例说明】2 -4 3 -1 2 -4 3
【数据规模与约定】
对于40%的数据,有N ≤ 2000。
对于100%的数据,有N ≤ 200000。
题解
动态规划
根据题目中n<=200000的范围限制,要想解决此题,必须寻找时间复杂度为O(n)的有效算法。容易想到采用动态规划来解决该问题。
用a[i]保存序列。
定义f[i]:以a[i]为连续子序列右边界(连续子序列的最右一个元素)的最大连续子序列的和。
容易得出方程:f[i]:=max{f[i-1]+a[i],a[i]} (1<=i<=n)
初始:f[1]=a[1];
目标:max{f[i]} (1<=i<=n)
下面附上代码。
代码
- program zdzdh;
- var
- a,ans:array[1..200000] of int64;
- n,i:longint;
- max:int64;
- begin
- readln(n);
- read(a[1]);
- ans[1]:=a[1];
- for i:=2 to n do
- begin
- read(a[i]);
- if ans[i-1]<0 then ans[i]:=a[i] else ans[i]:=ans[i-1]+a[i];
- end;
- max:=-maxlongint;
- for i:=1 to n do
- if ans[i]>max then max:=ans[i];
- writeln(max);
- end.
(本文系笔者原创,未经允许不得转载)